javascript - leaflet Js 自定义控制按钮添加(文本、悬停)

标签 javascript button leaflet

我关注了this control-button-leaflet tutorial它对我有用。现在我想:

  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);

最佳答案

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

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

    container.title="No cat";
    
  2. 还有一些文本而不是图像:

    container.value = "42";
    
  3. 您可以使用鼠标事件来设置按钮的样式:

    container.onmouseover = function(){
      container.style.backgroundColor = 'pink'; 
    }
    container.onmouseout = function(){
      container.style.backgroundColor = 'white'; 
    }
    

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

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

关于javascript - leaflet Js 自定义控制按钮添加(文本、悬停),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924890/

相关文章:

javascript - Google VR View - 托管代码不起作用

javascript - Vue 在标记任务之间切换不工作

javascript - 在 leafletjs map 中使用 Bing Quadkey tiles 而不是 x/y/z tiles

javascript - 如何在 Shiny/R 中创建自定义传单弹出样式

javascript - JavaScript 中的 DOM 性能

javascript - 显式类型 - 对象数组

javascript - 设置 Vuetify 复选框的初始值

android - fragment 中的按钮点击

php - 固化 "Back Button Blues"

css - 上升和下降按钮是如何制作的?