如何阻止点击穿透及其应用

点击穿透是什么

touchstart触发后,会在300ms内触发一个click的默认行为。

示例:
<!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>
      * {
      
      
        margin: 0;
        padding: 0;
      }
      .box {
      
      
        background-color: aqua;
        width: 95vw;
        height: 46vw;
        margin: auto;
        border: 1px solid black;
      }
      #mask {
      
      
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        line-height: 120px;
        background-color: rgba(0, 0, 0, 0.4);
        text-align: center;
        display: none;
      }
    </style>
  </head>

  <body>
    <div id="mask">轻触关闭遮罩层</div>
    <div class="box"></div>
    <button id="btn">弹出遮罩层</button>
    <script>
      const box = document.querySelector('.box');
      box.addEventListener('click', () => {
      
      
        alert('box is clicked');
      });
      const mask = document.querySelector('#mask');
      document.querySelector('#btn').addEventListener('click', () => {
      
      
        mask.style.display = 'block';
      });
      mask.addEventListener('touchstart', (e) => {
      
      
        e.target.style.display = 'none';
      });
    </script>
  </body>
</html>

在这里插入图片描述
触摸关闭遮罩层,发现box的click事件也被触发了。

阻止点击穿透

阻止默认行为,即可阻止点击穿透

mask.addEventListener('touchstart',(e)=>{
    
    
   e.preventDefault() // 阻止默认事件后,将不再触发触摸后的点击事件
   e.target.style.display='none'
})

实现点击穿透

应用:隐藏select默认下拉箭头,自定义icon图标,发现点击图标options不出现,这时需要用到点击穿透,给icon原素添加样式pointer-events: none;即可。

<div  class="select-box">
	<select id="selectLevel1" class="type-select-one" >
	</select>
	<i class="iconfont select-icon">&#xe607;</i>
</div>
.select-box {
    
    
	position: relative;
}
.type-select-one {
    
    
	width: 90%; 
	height: 84px;
	padding-left:12px;
	border: 1px solid #939393;
	appearance: none;
	outline: none;
	font-size: 50px;
}
.select-icon {
    
    
	position: absolute;
	top: 20px;
	right: 68px;
	width: 40px;
	height: 50px;
	color: #939393;
	font-size: 46px;
	pointer-events: none;
}

猜你喜欢

转载自blog.csdn.net/kwroi/article/details/128948294