javascript - 无法在固定位置关闭自定义弹出窗口
问题描述
这是一个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)
解决方案
您正在close
为创建弹出窗口之前添加事件侦听器。您应该layer.on('click', function(e){...
在onEachFeature
函数的末尾添加此侦听器。
为确保侦听器仅removeEventListener
添加了事件,请在添加事件之前使用。
推荐阅读
- c# - C# - 如何动态地与服务器进行身份验证
- c# - TableLayoutPanel 自动调整大小问题,行间空间大
- javascript - 获取对象数组中重复对象的列表
- c++ - 将文件读入内存 C++:std::strings 是否有 getline()
- widget - 如何处理和重新创建一些状态
- java - Java中涉及ArrayList索引的问题
- java - 如何在没有 Gradle 的情况下将 Gradle 项目转换为离线编译
- openstack - 安装openstack newton,即使它是EOL?
- common-lisp - Common Lisp 中的图遍历和搜索系统
- ios - 将用户重定向到特定的 ViewController - Swift 4