代码之家  ›  专栏  ›  技术社区  ›  user2906420

创建传单自定义复选框控件

  •  14
  • user2906420  · 技术社区  · 10 年前

    我想创建一个自定义的复选框控件,它只需在jquery/javascript中设置一个标志:如果选中了标志=“clustered”,或者如果未选中标志=“unclustered”。到目前为止,我在地图上有一个控件,但它不是一个复选框,我如何获得复选框的状态-如果它是选中/未选中的。

    代码:

    function MapShowCommand() {
      alert("checked / unchecked"); //set flag
    }
    
    L.Control.Command = L.Control.extend({
        options: {
            position: 'topleft',
        },
    
        onAdd: function (map) {
            var controlDiv = L.DomUtil.create('div', 'leaflet-control-command');
            L.DomEvent
                .addListener(controlDiv, 'click', L.DomEvent.stopPropagation)
                .addListener(controlDiv, 'click', L.DomEvent.preventDefault)
            .addListener(controlDiv, 'click', function () { MapShowCommand(); });
    
            var controlUI = L.DomUtil.create('div', 'leaflet-control-command-interior', controlDiv);
            controlUI.title = 'Map Commands';
            return controlDiv;
                }
        });
    var test = new L.Control.Command();
    map.addControl(test);
    
    2 回复  |  直到 10 年前
        1
  •  26
  •   YaFred    10 年前

    您必须在controlDiv中创建一个带有输入type=“checkbox”的表单元素。

    // create the control
    var command = L.control({position: 'topright'});
    
    command.onAdd = function (map) {
        var div = L.DomUtil.create('div', 'command');
    
        div.innerHTML = '<form><input id="command" type="checkbox"/>command</form>'; 
        return div;
    };
    
    command.addTo(map);
    
    
    // add the event handler
    function handleCommand() {
       alert("Clicked, checked = " + this.checked);
    }
    
    document.getElementById ("command").addEventListener ("click", handleCommand, false);
    

    在这个jsfiddle中工作 http://jsfiddle.net/FranceImage/ao33674e/

    您也可以通过传单的方式阅读以下提示: https://github.com/Leaflet/Leaflet/blob/master/src/control/Control.Layers.js

        2
  •  5
  •   Anton vBR    6 年前

    我对此感到困惑,尽管接受的答案指向了我正确的方向,但我还是在推特上添加了适当的内容 css 类。

    function toggleFunction(bool) {
      alert(bool)
    }
    
    var command = L.control({position: 'topright'});
    command.onAdd = function (map) {
        var div = L.DomUtil.create('div');
        div.innerHTML = `
        <div class="leaflet-control-layers leaflet-control-layers-expanded">
          <form>
            <input class="leaflet-control-layers-overlays" id="command" 
              onclick=toggleFunction(this.checked) type="checkbox">
              Toggle
            </input>
          </form>
        </div>`; 
        return div;
    };
    command.addTo(mymap); //your map variable
    

    结果:

    enter image description here