简体   繁体   English

Vanilla JS-在元素外部切换类

[英]Vanilla JS - Toggle class outside element

Like in topic. 喜欢主题。 I search other way to do this, but it won't work good. 我搜索其他方法来执行此操作,但效果不佳。 After using button immediately function give me "removing" :/ Any lead to a good lead? 使用立即按钮功能后,请给我“删除”:/有没有好的引线?

var button = document.querySelector(".menu-icon");
var menu = document.querySelector(".mymenu");

function drop(e){
  menu.classList.add("show");
  document.addEventListener("click", hide(e));
}
function hide(e){
  if(!menu.contains(e.target)) menu.classList.remove("show");
}
button.addEventListener("click", drop);

Well first of all, you need to parse the hide function into 'addEventListener', not call it, that will parse the return of the function (null), and call it immediately and not on click. 首先,您需要将hide函数解析为'addEventListener',而不是对其进行调用,这将解析该函数​​的返回值(null),并立即对其进行调用,而不是单击。

So it would look like this instead: 因此它看起来像这样:

function drop(e) {
  menu.classList.add('show');
  document.addEventListener("click", hide); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM