点击一个元素,影响它后面的内容

Click through an element, affecting what's behind it

本文关键字:影响 元素 一个      更新时间:2023-09-26

所以,我要为我的网站做一个覆盖的东西,一个元素被固定在网站上,放在所有东西的上面。但是这意味着元素后面的任何东西都不能被影响。

这是一个重现这个问题的JSFiddle。

你会注意到你不能突出显示黑色文本,JavaScript事件也不会触发。


下面是我用来创建这个问题的CSS + HTML:

HTML

<div id="main-container">
    <div id="container-content">You can't highlight me! D:</div>
    <div id="container-fixed"><div style="margin:90px auto;background:red;width:40px;height:40px;"></div>You cannot highlight the text behind this DIV.  It also doesn't fire click events.</div>
</div>

main-container:保存内容。

container-content:这是固定DIV后面的内容

container-fixed:这是DIV重叠的"container-content"

CSS

#main-container {
    width: 90%;
    margin: 5%;
    position: relative;
    height: 500px;
    overflow: auto;
}
#container-content {
    width: 100%;
    height: auto;
}
#container-fixed {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    color: red;
}

我想要达到的是可能的吗?CSS和JavaScript (jQuery)的答案都是允许的。

使用CSS pointer-events:

值none除了指示该元素不是鼠标事件的目标外,还指示鼠标事件"穿过"该元素,并以该元素"下面"的内容为目标。

#container-content {
    width:100%;
    height:auto;
    pointer-events: none;
}

如果你需要支持ie10或更低版本,这里有一个polyfill

这应该能奏效:

#container-fixed{
    pointer-events: none;
}

pointer-events: none;禁用鼠标在目标元素上的交互。
请注意,IE 11之前的版本不支持此CSS属性

对于IE10>浏览器,你必须通过高级元素计算你想要点击的元素的位置,然后做你想做的事情。例如http://jsfiddle.net/hm6Js/7/

topo=$('#container-content').offset().top;
left=$('#container-content').offset().left;
right=$('#container-content').offset().left+$('#container-content').width();
bottom=$('#container-content').offset().top+$('#container-content').height();
$(document).click(function(e){
    if(e.pageX>=left && e.pageX<=right && e.pageY>=topo && e.pageY<=bottom){
        alert("This doesn't work.");
    }
});

就像你在这个例子中看到的那样,警报只在你点击#container-content元素时触发。

注意:

如果你想要点击很多元素,这不是最有效的方法。

你可以通过css的指针事件来做到这一点。把#container-content的css改成

#container-content{
width:100%;
height:auto;
}
#container-fixed {
width:100%;
height:100%;
position:absolute;
top:0; left:0;
color:red;
    pointer-events: none /*the important thing*/
}

working fiddle here

指向指针事件更多信息的链接可以在这里找到这可能不是跨浏览器,但另一个家伙建议,如果这是一个问题)使用javascript,通过层转发鼠标事件。完整答案可以在这里找到

可以添加z-index

#container-content {
 width:100%;
 height:auto;
  z-index:999;
  position:absolute;
}