[英]How can I cancel the click from window.onclick in javascript
I'm trying to create a burguer menu and when I click outside the burguer menu it closes like I wanted, but it just continues the click and goes wherever I clicked to leave the burguer menu 我正在尝试创建一个汉堡菜单,当我在汉堡菜单外部单击时,它会按我的意愿关闭,但它会继续单击并继续到我单击的任何位置以离开汉堡菜单
window.onclick = function () {
if ($scope.showMenuContent) {
$scope.showMenuContent = false;
$scope.$apply();
}
};
I'm using angular js too, so the variable showMenuContent shows and hides my burguer menu. 我也使用了角度js,因此变量showMenuContent显示和隐藏我的汉堡菜单。
I have already tried to stop propagation like this 我已经试图阻止这种传播
window.onclick = function (event) {
event.stopPropagation();
if ($scope.showMenuContent) {
$scope.showMenuContent = false;
$scope.$apply();
}
};
but it does not work! 但它不起作用!
我通过在关闭菜单时删除eventlistener并在打开时添加来实现了
Its not a good practice to add and remove event listeners very often. 经常添加和删除事件侦听器不是一个好习惯。 What you can rather do is add a permanent event listener to the window and check whether the click was on the menu or not by using event.toElement.id and then take actions accordingly. 您可以做的是在窗口中添加一个永久事件侦听器,并使用event.toElement.id检查单击是否在菜单上,然后采取相应的措施。
let burger = document.getElementById('burger'), isOpen = false; const closeMenu = e => { let _target = e.toElement.id; if(_target != 'burger' && isOpen) { //This will close if burger is open and you click elsewhere burger.classList.remove('open'); isOpen = false; } } const toggleMenu = () => { if (!isOpen) { //opens the menu burger.classList.add('open'); isOpen = true; } else { //closes the menu burger.classList.remove('open'); isOpen = false; } } window.addEventListener('click', closeMenu, false);
#burger { width: 50px; height: 50px; background: red; cursor: pointer; } .open { width: 300px !important; height: 300px !important; background: black !important; }
<div id="burger" onclick="toggleMenu()"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.