定位将禁用悬停选择器和鼠标悬停事件

Positioning disables hover selector and mouseover events

本文关键字:悬停 鼠标 事件 选择器 定位      更新时间:2023-09-26

这个jsfidd。。

https://jsfiddle.net/9e1wd245/12/

演示了一种浏览器行为,我想比现在更好地理解它。

如果从crumbtray和crumb中移除定位,则悬停选中的CSS将在crumb悬停时应用,鼠标进入crumb时将触发鼠标悬停事件。

定位到位后,这两件事都不会发生;但是,如果您将鼠标悬停在顶部边界上,则会应用悬停CSS并触发mouseover事件。

(在这种情况下,使用的方法使用定位来实现z索引,这样弯曲的右边界将出现在相邻元素的左侧。)

请注意,你可以去掉碎屑上的负右边距,问题仍然存在,所以它不是由负边距引起的。

我意识到我可以使用svg作为crumb,或者在共享背景上使用几个分隔符元素,而不是使用定位和z索引,但为什么这不起作用?规范中是否有说明悬停和鼠标悬停事件不适用于已定位的元素?还有什么我完全忽略了的吗?

html:

<div class="crumbtray">
    <span class="crumb">USA</span>
    <span class="crumb">California</span>
    <span class="crumb">Sacremento</span>
</div>

css:

.crumbtray {
    position: relative;
    top: 0px;
    left: 0px;
    display: inline;
    z-index: -10;
    font-family: ariel, sansserif
    font-size: 12px;
}
.crumb { 
    position: relative;
    top: 0px;
    left: 0px;
    display: inline;
    border: solid 1px gray;
    border-left: none;
    border-radius: 0px 10px 10px 0px;    
    padding: 0px 8px 0 12px;
    margin-right: -10px;
    cursor: pointer;
    background: #c3f4c6;
    background: -moz-linear-gradient(top,  #c3f4c6 0%, #96f788 8%, #98e0a4 92%, #419330 96%, #188700 100%);
    background: -webkit-linear-gradient(top,  #c3f4c6 0%,#96f788 8%,#98e0a4 92%,#419330 96%,#188700 100%);
    background: linear-gradient(to bottom,  #c3f4c6 0%,#96f788 8%,#98e0a4 92%,#419330 96%,#188700 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#c3f4c6', endColorstr='#188700',GradientType=0 );
}
.crumb:hover {
    background: none;
    background-color: yellow;
}
.crumb:first-child {
    border-left: solid 1px gray;
    z-index: 60;
    padding-left: 2px;
}
.crumb:nth-child(2) {
    z-index: 50;
}
.crumb:nth-child(3){
    z-index: 40;
}

JavaScript:

var ViewModel = {
    init: function(){
        console.log("ViewModel.init called");
        $('.crumbtray').on('mouseover','span',function(){
            console.log('mouseover crumb: ', this);
        });
    }
};
$(ViewModel.init);

您的问题在这里:

z-index: -10;

这将元素放在背景后面,这意味着尽管您可以看到它,但鼠标无法"看到"它,因为它位于(透明)背景后面,因此它不会接收鼠标悬停事件。

现在,它应该仍然有效,因为.crumb在背景上方具有正z索引。很可能只是一个bug,我不相信这种行为在任何地方都有记录。

它不起作用,因为您已经为父元素设置了负z索引(为什么要这样做?)。只需将其从那里移除或更改为一些正值,例如1

当您将负z索引设置为元素时,它会创建所有子元素的负堆叠上下文,因此z索引宽度40、50、60在其父元素内部是有意义的,但主z索引将为负(在主体元素下)。

所以主要的问题是负z索引,你可以剪切它并用"负z索引悬停"关键字搜索一些信息来清除

.crumbtray {
    position: relative;
    top: 0px;
    left: 0px;
    display: inline;
    z-index: -10;
    font-family: ariel, sansserif
    font-size: 12px;
}