阻止元素的click、hover、active的触发
tab栏,在切换菜单时,需要对已经选中的菜单做处理,防止再次点击选中的菜单也会触发请求或其他的操作
<div class="list">
<ul>
<li class="active li">列表1</li>
<li class="li">列表2</li>
<li class="li">列表3</li>
<li class="li">列表4</li>
</ul>
</div>
.list ul{
list-style: none;
margin: 0;
padding: 0;
display:flex;
}
.list ul li+li{
margin-left:10px;
}
.list ul li.active{
border-bottom: 1px solid red;
pointer-events: none;
}
.list ul li:hover{
color: magenta;
}
const lis = Array.from(document.getElementsByClassName("li"))
lis.forEach((li,idx)=>{
li.onclick=function(){
console.log(idx)
}
})
阻止事件点击
- 请求没有完成前,阻止继续触发事件
- 点击触发事件,每隔一段时间才能重新触发(节流效果)
<button class="btn">点击</button>
.btn.active{
pointer-events: none;
}
const btnDom = document.querySelector(".btn")
btnDom.onclick=function(){
console.log("点击")
btnDom.classList.add("active")
setTimeout(()=>{
btnDom.classList.remove("active")
},1000)
}
事件透传
某个插件渲染出来的按钮,点击事件只能设置在这个按钮上,但是需要好看一点的按钮,修改插件渲染出来的按钮又特别麻烦,此时就可以考虑在按钮上覆盖一层,然后在这一层做我们需要的样式,并设置
pointer-events
属性,让点击覆盖层时,事件能够透传到下面
插件渲染出来的按钮
覆盖一层并修饰的样式
<h1>事件穿透</h1>
<div class="box">
<button class="btn1">点击</button>
<div class="box1">覆盖样式</div>
</div>
.box {
position: relative;
}
.box .btn1{
width: 100px;
height: 50px;
}
.box .box1{
position: absolute;
top: 0;
width: 100px;
height: 50px;
background: magenta;
pointer-events: none;
}
const btn1Dom = document.querySelector(".btn1")
btn1Dom.onclick=function(){
alter("触发了btn1的点击事件")
}