前端——点击遮罩层没有内容的地方进行隐藏

1,335 阅读2分钟

在项目中遇到的问题,在PC端或手机端的遮罩层,为了给用户更好的体验,需要在点击遮罩层中弹窗隐藏,点击内容弹窗不能隐藏。

这个主要用的知识点是事件的冒泡和捕获

事件的冒泡:是从里向外,DOM的层次像冒泡一样,不断的向上一级上升

事件的捕获:事件捕获指的是从document到触发事件的那个节点,即自上而下的去触发事件

注意:1.ie只有事件的冒泡没有事件的捕获

         2,事件的捕获会先发生

先了解一下实践冒泡和捕获事件:

HTML结构:

     <div id="parent">             <div id="child" class="child"></div>      </div>

现在给他们绑定事件:

      document.getElementById("parent").addEventListener("click",function(e){                  alert("parent事件被触发,"+this.id);      })            document.getElementById("child").addEventListener("click",function(e){             alert("child事件被触发,"+this.id)     })

结果:

child事件被触发,child
parent事件被触发,parent

结论:

      先child,然后parent。事件的触发顺序自内向外,这就是事件冒泡。 现在改变第三个参数的值为true

document.getElementById("parent").addEventListener("click",function(e){
                alert("parent事件被触发,"+e.target.id);
            },true)
document.getElementById("child").addEventListener("click",function(e){
                alert("child事件被触发,"+e.target.id)
            },true)

结果:

parent事件被触发,parent
 child事件被触发,child

结论:

     先parent,然后child。事件触发顺序变更为自外向内,这就是事件捕获

点击遮罩层,弹窗隐藏的例子:

CSS样式:

<style>     .popup {display:none;position:fixed;width:100%;height:100%;left:0;top:0;z-index:300;background:rgba(0,0,0,0.6);filter:Alpha(opcity=60);overflow: auto;}     .abc{width: 100%;height: 100px;background-color: wheat       .popup_hide{background-color: white;width: 100%;height: 100px;}</style> 

HTML文件:

     <div class="abc"> 点我出现遮罩层哦 </div>     <div class="popup">            <div class="popup_hide"> asdfghjbvcsa </div>     </div>

JS文件:

<script>
      $('.abc').on("click",function(){  
        $('.popup').show();  
    });  //点击的popup使整个遮罩层进行隐藏
      $(".popup").on("click",function(){  
        $(this).hide();  
    });  //使popup_hide的父元素popup阻止,不会触发了这个事件
从而使点击popup_hide以外的内容将遮罩层进行隐藏
      $(".popup .popup_hide").on("click",function(e){  
        e.stopPropagation();  
    })  //点击内容块(.popup_hide)阻止了事件的冒泡
 </script>   

注意:要引jquery文件