js实现点击按钮出现元素,点击其他地方隐藏该元素

首先为控制出现消失的被点击元素添加点击事件,并且使用stopProp()函数防止该元素上的事件冒泡。然后给body添加点击事件,点击时需要消失的元素添加属性display: none;,这样变可以实现点击其他区域该元素消失。
注意几点:

  1. 初始display: none;属性需要设置成行内样式,否则会导致element.style.dispaly方法第一次获取不到值而需要点击两次才能看到效果。如果非要设置成外联样式,可以使用window.getComputedStyle(element, [pseudoElt]);方法获取。具体参考:MDN getComputedStyle方法
  2. stopPropagation()cancelBubble()方法为阻止事件冒泡的方法,其中stopPropagation()符合W3C标准,适用于Chrome、Firefox等浏览器。cancelBubble不符合W3C标准,适用于IE浏览器。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      width: 100%;
      height: 500px;
    }
    #outside {
      width: 200px;
      height: 50px;
      background-color: aquamarine;
    }
  </style>
</head>
<body>
  <div id="outside">
    点击这里出现列表
  </div>
  <div id="modal" style="display: none;">
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>

  <script>
    window.onload = function () {
      const outside = document.getElementById("outside");
      outside.addEventListener("click", viewModal);
      const body = document.getElementsByTagName("body")[0];
      body.addEventListener("click", hideModal);
      const modal = document.getElementById("modal");
      // 防止点击 modal 列表时列表消失
      modal.addEventListener("click", (e) => { stopProp(e); });
    }
    function viewModal (e) {
      stopProp(e);  // 防止事件冒泡导致触发body上绑定的点击事件
      const modal = document.getElementById("modal");
      const disp = modal.style.display;
      modal.style.display = disp === "none" ? "block" : "none";
    }
    function hideModal () {
      const o = document.getElementById("modal");
      o.style.display = "none";
    }
    /**
     * 阻止事件冒泡
    */
    function stopProp (e) {
      e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
    }
  </script>
</body>
</html>

参考:
https://www.cnblogs.com/sghy/p/10044313.html
https://blog.csdn.net/gmd_web/article/details/49661091

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值