拜托,我的 JS 代码有问题我构建了这段代码,因为我希望当访问者单击另一个 div(不是菜单)时,如果菜单打开,菜单将关闭 这是代码,但此代码不适用于手机,但它适用于 chrome 或 firefox 的开发人员工具
<script>
window.addEventListener('mouseup', function(event){
var box = document.getElementById('narvbar_menu');
if (event.target != box && event.target.parentNode != box){
box.style.display="none";
document.getElementById("close_menu").style.display="none";
}
});
</script>
最好的问候
最佳答案
这是因为 "mouseup"
不会在移动设备上触发。还要听取 "touchend"
:
编辑: 下面的代码应该将 "mouseup"
和 "touchend"
的事件监听器附加到窗口。
<script>
["mouseup", "touchend"].forEach(function(e) {
window.addEventListener(e, function(event){
var box = document.getElementById('narvbar_menu');
if (event.target != box && event.target.parentNode != box){
box.style.display="none";
document.getElementById("close_menu").style.display="none";
}
});
})
</script>
如果您不想监听多个事件,“click”
应该适用于移动设备和桌面设备:
window.addEventListener("click", function(event) { ... }
关于javascript - window.addEventListener 代码不适用于移动设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54484606/