如何防止 Leaflet 地图元素获得焦点

4

我有一个表单,其中包含一个leaflet地图。我想通过按tab键在元素之间移动,并且不希望地图或其元素(按钮、标记等)获得焦点。我该如何添加tabindex="-1"到地图控件和元素以防止获取焦点,或者我可以做什么来防止获取焦点?

这里是一个jsfiddle演示我的情况:http://jsfiddle.net/kedar2a/LnzN2/2/

var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', osmAttrib = '&copy; <a ref="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
       osm = L.tileLayer(osmUrl, {attribution: osmAttrib  });

var map = L.map('map').setView([19.04469, 72.9258], 12).addLayer(osm);

var marker = L.marker([19.04469, 72.9258]).addTo(map);
#map {
    height: 150px;
    width: 300px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.js"></script>
<input type="text" autofocus />
<div id="map"></div>
<input type="text"  />

1个回答

3

没有一种简单的解决方案,但您可以通过以下三个步骤禁用每个地图元素来实现此目标:

  1. Disable focus for markers: Disable keyboard support for markers by adding keyboard:false to the marker element.

  2. Add tabIndex="-1" attribute to all <a> elements located inside .leaflet-control divs

    var elements = document.querySelectorAll(".leaflet-control a");
    for (var i = 0; i < elements.length; ++i) {
      elements[i].setAttribute("tabindex", "-1");
    }
    
  3. Disable focus for Close Button inside any open marker popup.

      var marker = L.marker(e.latlng, {
          draggable: true,
          keyboard: false,
          title: "Resource location",
          alt: "Resource Location",
          riseOnHover: true
        }).addTo(map)
        .bindPopup(e.latlng.toString()).on('popupopen',
          function(popup) {
            //disable focus of close button
            var elCloseButton = document.getElementsByClassName("leaflet-popup-close-button")[0];
            elCloseButton.setAttribute("tabindex", "-1");
          }).openPopup();
    

请查看我的实现:http://jsfiddle.net/trkaplan/bv763tkf/


2
嗨@trkaplan,你的解决方案非常好。我唯一需要更改的是:将var elements = document.querySelectorAll(". Leaflet-control a, .leaflet-container");更改为防止.leaflet-container也获得焦点。 - Gringo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接