首页 > 解决方案 > 无法在固定位置关闭自定义弹出窗口

问题描述

这是一个javascript初学者问题。我在固定位置(传单)创建了一个自定义弹出窗口。单击打开弹出窗口的标记后,我无法通过单击关闭按钮来关闭它。虽然我可以单击不同的标记,但弹出包装仍然打开,显示附加到每个不同标记的内容。因此,弹出窗口的内容通过单击标记更改,但无法通过单击关闭按钮关闭弹出窗口。
我尝试了一个事件监听器。我需要完成这项工作的那段代码。任何帮助,将不胜感激。

// Adds custom marker

var redFlag = L.icon({
    iconUrl: 'images/mapmarker2.png',
    iconSize: [34, 34],
    iconAnchor: [17,34]
});

// Adds markers and popup
// geoJSON file stored in 'art' variable

const myLayer = L.geoJSON(art, {
    pointToLayer: function (feature, latlng) {
          return L.marker(latlng, {icon: redFlag});

},
onEachFeature: function ( feature, layer) {
    layer.on('click', function(e){

// popup content

   var getWrap = document.getElementById('wrapper');
        var wrap = getWrap.appendChild(document.createElement('div'));
        wrap.className = 'wrapper';
        wrap.innerHTML =  
           `<div class="close">X</div>`+ 
           `<div class="popUpContent" style="background-color:#e8f4ff">`+
           `<div class='pic'><img src = 
            "images/${feature.properties.image}"></div>`+ 
           `<div class="puName"><span 
            class="puName">${feature.properties.name}</span><br>`+
           `<span class="puTitle">"${feature.properties.title}"</span><br>`+ 
           `<div class="extra3">${feature.properties.extra}</div></div>`+ 
           `</div>`;

    if(!feature.properties.title){

        wrap.innerHTML =  
            `<div class="close">X</div>`+
            `<div class="popUpContent" style="background-color:#e8f4ff">` + 
             `<div class='pic'><img src = 
             "images/${feature.properties.image}"></div>`+ 
             `<div class="puName"><span 
             class="puName">${feature.properties.name}</span><br>`+ 
             `<div class="extra3">${feature.properties.extra}</div></div>`+ 
             `</div>`;
         }

// Add eventlistener to the close button

document.querySelector('.close').addEventListener( 'click', closePopup);
      function closePopup(e){

        if(event.target.matches('.close')){
            document.querySelector(".wrapper").style.display='none'
        }else if(document.querySelector(".wrapper").style.display='block'){
            document.querySelector(".wrapper").style.display='none';
           }
         }

       });
    }

});

mymap.addLayer(myLayer)

标签: javascriptpopupleaflet

解决方案


您正在close为创建弹出窗口之前添加事件侦听器。您应该layer.on('click', function(e){...onEachFeature函数的末尾添加此侦听器。

为确保侦听器仅removeEventListener添加了事件,请在添加事件之前使用。


推荐阅读