删除事件点击JavaScript [重复]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了删除事件点击JavaScript [重复]相关的知识,希望对你有一定的参考价值。
这个问题在这里已有答案:
我有两个功能来打开和关闭sidenav
。我添加了功能,当你点击外部导航时你触发功能closeNav()
。 Sidenav已关闭,但事件点击仍然在整个document
,所以我必须removeEventListener
。我已经尝试了很多,但没有尝试是有效的。任何想法如何做到这一点?
JS
// Show sidenav
var sideNav = document.getElementById('rizkSidenav');
function openNav() {
sideNav.style.width = "83%";
// Close nav when clicked outside
document.addEventListener("click", function(evt) {
targetElement = evt.target; // clicked element
do {
if (targetElement === sideNav) {
// This is a click inside. Do nothing, just return.
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
// This is a click outside.
closeNav();
});
}
function closeNav() {
sideNav.style.width = "0";
//????? (event listener should be removed)
document.removeEventListener("click", function(evt){});
}
答案
因为它的功能不一样。试试这个:
var sideNav = document.getElementById('rizkSidenav');
var myFunction = function(evt) {
targetElement = evt.target; // clicked element
do {
if (targetElement === sideNav) {
// This is a click inside. Do nothing, just return.
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
// This is a click outside.
closeNav();
}
function openNav() {
sideNav.style.width = "83%";
// Close nav when clicked outside
document.addEventListener("click", myFunction);
}
function closeNav() {
sideNav.style.width = "0";
//????? (event listener should be removed)
document.removeEventListener("click", myFunction);
}
以上是关于删除事件点击JavaScript [重复]的主要内容,如果未能解决你的问题,请参考以下文章