传单Js自定义控件按钮添加(文本,悬停)

Jer*_*nts 11 javascript button leaflet

我按照这个控制按钮 - 传单教程,它对我有用.现在我想:

  1. 当我将鼠标悬停在按钮上时显示一些文字(与缩放按钮一样)
  2. 将鼠标悬停在按钮上时更改按钮的颜色
  3. 能够在按钮内写入文本而不是图像.

这是代码:

    var customControl =  L.Control.extend({        
      options: {
        position: 'topleft'
      },

      onAdd: function (map) {
        var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom');

        container.style.backgroundColor = 'white';     
        container.style.backgroundImage = "url(http://t1.gstatic.com/images?q=tbn:ANd9GcR6FCUMW5bPn8C4PbKak2BJQQsmC-K9-mbYBeFZm1ZM2w2GRy40Ew)";
        container.style.backgroundSize = "30px 30px";
        container.style.width = '30px';
        container.style.height = '30px';

        container.onclick = function(){
          console.log('buttonClicked');
        }

        return container;
      }
    });

    var map;

    var readyState = function(e){
      map = new L.Map('map').setView([48.935, 18.14], 14);
      L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
      map.addControl(new customControl());
    }

    window.addEventListener('DOMContentLoaded', readyState);
Run Code Online (Sandbox Code Playgroud)

Krx*_*dfx 14

看来你需要一个Button而不是div:

    var container = L.DomUtil.create('input');
    container.type="button";
Run Code Online (Sandbox Code Playgroud)
  1. 然后,您可以轻松设置鼠标悬停文本:

    container.title="No cat";
    
    Run Code Online (Sandbox Code Playgroud)
  2. 而一些文字而不是图像:

    container.value = "42";
    
    Run Code Online (Sandbox Code Playgroud)
  3. 您可以使用鼠标事件来设置按钮的样式:

    container.onmouseover = function(){
      container.style.backgroundColor = 'pink'; 
    }
    container.onmouseout = function(){
      container.style.backgroundColor = 'white'; 
    }
    
    Run Code Online (Sandbox Code Playgroud)

(你当然可以用css做最后一部分,可能更优雅)

完整示例:http://codepen.io/anon/pen/oXVMvy

  • https://jsfiddle.net/4wfrqm1k/ 适合因某种原因在 codepen 上看不到“运行”选项的任何人。 (2认同)