Home >Web Front-end >JS Tutorial >How to achieve mask effect in js

How to achieve mask effect in js

王林
王林forward
2020-04-06 09:18:352397browse

How to achieve mask effect in js

Let’s analyze the ideas:

1. Monitor button clicks

2. Prevent bubbling (the most critical point)

3. Let the hidden ones show up

4. Hide the scroll bar

5. Click on the document: Get the clicked label

Judgment: Hide all the displayed ones

Show scroll bar

<style>
    *{
      margin: 0;
      padding: 0;
    }
    html,body{
      width:100%;
      height:100%;
    }
    #panel{
      width:100%;
      height:2000px;
      background-color:#000;
      opacity: 0.4;  //透明度
      filter: alpha(opacity: 40);  //用于兼容IE浏览器
      position: absolute;
      top:0;
      left:0;
      display: none;
    }
    #box{
      width:300px;
      height:300px;
      background-color: #fff;
      position: absolute;
      top:50%;
      left:50%;
      margin-left:-150px;
      margin-top:-150px;
      display: none;
      border-radius: 5px;
    }
  </style>
</head>
<body>
  <button id="btn">登录</button>
  <div id="panel"></div>
  <div id="box"></div>
  <script src="js/myFunc.js"></script>
  <script>
    window.onload = function (){
      //1.监听事件的点击
      btn.onclick = function (event){

        //1.0 阻止冒泡
        if(event && event.stopPropagation){ //W3c标准
         event.stopPropagation();
        }else{ //IEx系列 IE 678
         event.cancelBubble = ture;
        }
        //1.1隐藏的显现出来
        $("box").style.display = "block";
        $("panel").style.display = "block";
        //1.2隐藏滚动条
        document.body.style.overflow = "hidden";
      }
      //2.点击文档
      document.onclick = function (event){
        var e = event || window.event;
        //2.1获取点击的标签
        var tranId = e.target ? e.target.id : e.srcElement.id;  //target:获取当前操作对象
        //2.2判断
        if(tranId !== "box"){
          //1.1显示的隐藏出来
          $("box").style.display = "none";
          $("panel").style.display = "none";
          //1.2显示滚动条
          document.body.style.overflow = "auto";
        }else{
          window.location.href = "http://www.baidu.com";
        }

      }
    }
</script>

The most important point is to prevent events from bubbling up.

Get the id of the object:

var tranId = e.target ? e.target.id : e.srcElement.id;

Recommended related tutorials: js tutorial

The above is the detailed content of How to achieve mask effect in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete