【问题标题】:Close by clicking outside with plain javascript通过使用纯 javascript 在外部单击关闭
【发布时间】:2018-05-21 03:38:10
【问题描述】:

我想在菜单按钮区域外单击时关闭菜单(打开时删除添加的类)。

我得到了一切工作,但想知道我放在一起的代码是否正确,因为我认为只有在将 .newClass 添加到 div 时才应该触发外部点击。如果是这样,我该如何添加?我对javascript很陌生。

var b = document.getElementById("menu");
document.addEventListener("mouseup", function(event) {
  var clickOnMenu = b.contains(event.target);
  if (clickOnMenu) {
    b.classList.toggle("newClass");
  } else {
    b.classList.remove("newClass");
  }
});
div.box {
  margin: auto;
  padding: 1em;
  max-width: 6em;
  background: rgba(0, 0, 0, 0.6);
  text-align: center;
  color: white;
  transition: .2s ease-in-out;
  cursor: pointer;
}

div.box:hover {
  background: rgba(0, 0, 0, 0.7);
}

div.newClass {
  padding-bottom: 100px;
}
<div id="menu" class="box">Menu</div>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    希望对你有帮助

    var b = document.getElementById("menu");
    document.addEventListener("mouseup", function(event) {
      var x = event.target.id;
      if(x == "menu" ) {
        b.classList.add("newClass");
      } else {
        b.classList.remove("newClass");
      }
    });
    div.box {
      margin: auto;
      padding: 1em;
      max-width: 6em;
      background: rgba(0, 0, 0, 0.6);
      text-align: center;
      color: white;
      transition: .2s ease-in-out;
      cursor: pointer;
    }
    
    div.box:hover {
      background: rgba(0, 0, 0, 0.7);
    }
    
    div.newClass {
      padding-bottom: 100px;
    }
    <div id="menu" class="box">Menu</div>

    【讨论】:

    • 谢谢,但是每次点击外部都会触发外部点击吗?我认为它应该只在类 .newClass 添加到 div 时触发?!
    • 是的,在事件监听器中添加一个console.log() 来检查它。您在document@MathiasN 上定义您的活动
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多