我有一个将指针事件设置为无的元素,这样就不会显示子元素的悬停样式。
但是当点击这个元素时,我想用JavaScript做点什么。在JavaScript中使用onclick事件似乎不起作用,因为指针事件设置为无。
有没有解决方法,以便我可以拥有一个没有指针事件的元素仍然可以触发JavaScript事件?
[data-drawer="open"] {
.site-drawer {
transform: translateX(0);
transition: all .2s ease;
}
.site-container {
transform: translateX(-27.5rem);
// Disabling pointer events disables styles hover styles on below elements
// But also disables clicking on container to remove it.
pointer-events: none;
transition: all .2s ease;
&:after {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,.75);
content: "";
}
}
}
JavaScript的:
this.siteContainer.addEventListener('click', (e) => {
console.log('site container clicked');
if(document.body.hasAttribute('data-drawer')) {
document.body.removeAttribute('data-drawer');
}
});
干杯
答案 0 :(得分:0)
正如我在评论中提到的,您可以通过使用pseudo-elements和z-index
在内容上添加不可点击的叠加层来实现此目的基本上你有四层。
结果:用户无法在模式内单击,但可以在第2层的任何位置点击外部
粗略的例子:
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: 0;
pointer-events: none;
background: rgba(0, 0, 0, .5)
}
.close {
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: 0;
display: none;
z-index: 1;
position: fixed;
cursor: default;
}
.modal-content:after {
content: "";
left: 0;
position: absolute;
top: 0;
width: 100%;
height: 100%;
z-index: 2;
}
.modal:target {
opacity: 1;
pointer-events: auto;
}
.modal:target>.close {
display: block;
}
.modal>div {
width: 300px;
text-align: center;
padding: 40px;
z-index: 2;
position: relative;
background: red;
}
.wrap,
.modal {
display: flex;
align-items: center;
justify-content: center
}
<div class="wrap">
<a href="#M"><button>You can click me!</button></a>
<div id="M" class="modal">
<div class="modal-content">
<a href="#"><button>But not me!</button></a>
</div>
<a href="#" class="close"></a>
</div>
</div>
答案 1 :(得分:0)
您可以使用此工作。将pointer-events: none
设置为具有悬停效果的元素,并将“包装器div”添加到仍需要在单击时触发的元素。
$(".cant-click-this").on("click", function(ev) {
console.log("You cant trigger the element, and it has no hover effects.");
});
$(".click-me-instead").on("click", function(ev) {
console.log("You can trigger click through the wrapper.");
});
&#13;
.cant-click-this {
pointer-events: none;
}
.cant-click-this:hover {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click-me-instead">
<button class="cant-click-this"> Try to click me</button> <br>Hovering is futile.
</div>
&#13;