当我将鼠标悬停在 .mensal
DIV 上时,它会触发鼠标悬停在父 .opera
DIV 上,这对我来说似乎是错误的。我只想让“突出显示”效果在子 .opera
DIV 上工作。
#operaContent {
padding: 0 50px 0 50px;
position: relative;
overflow: visible;
}
#operaContent .opera {
display: block;
border: 1px solid #FFFFFF;
border-bottom: 1px solid #DDDDDD;
padding: 5px;
margin-bottom: 10px;
height: 120px;
background-color: #0A8ECC;
}
#operaContent .opera:hover {
border: 1px solid #AAAAAA;
background-color: #DDDDDD;
cursor: pointer;
}
.mensal {
position: absolute;
top: 1px;
left: 8px;
z-index: 3;
display: block;
}
<div id="operaContent">
<div class="opera">
<div class="mensal">
DIV
</div>
</div>
</div>
最佳答案
根据定义,悬停在子项上,也会悬停在父项上。 html事件中没有“阻塞”。
有两个方法链,bubble 和 capture。
Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.
http://www.quirksmode.org/js/events_order.html
要阻止这种情况的唯一方法是通过向页面添加 javascript 来防止冒泡以防止链。这在 jQuery 中很简单
$('.mensal').hover(function(e){
e.stopPropagation();
});
我突然想到这个答案在处理 CSS 时完全没有帮助。 Javascript 事件不处理 CSS 选择器或阻止它们。
不幸的是,仅使用 CSS,我不知道有什么方法可以完成此操作(即使在 javascript 中也可能变得棘手)。 CSS 4 选择器将允许您指定选择器的主题 http://dev.w3.org/csswg/selectors4/#subject这样你就可以做类似的事情
#operaContent .opera:hover! .mensal:not(:hover) { /*your css*/ }
但这还没有实现,并且仍在为草案制定。
编辑: 这是一个适合您的 javascript (jQuery) 实现
$(function(){
$('.opera').hover(function() {$(this).addClass('hoverIntent')},
function(){ $(this).removeClass('hoverIntent'); }
);
$('.opera .mensal').hover(function() {
$(this).parent('.opera').removeClass('hoverIntent');
});
})
和修改后的 CSS
#operaContent {
padding: 0 50px 0 50px;
position: relative;
overflow: visible;
}
#operaContent .opera {
display: block;
border: 1px solid #FFFFFF;
border-bottom: 1px solid #DDDDDD;
padding: 5px;
margin-bottom: 10px;
height: 120px;
background-color: #0A8ECC;
}
#operaContent .opera.hoverIntent {
border: 1px solid #AAAAAA;
background-color: #DDDDDD;
cursor: pointer;
}
.mensal {
position: absolute;
top: 1px;
left: 8px;
z-index: 3;
display: block;
}
和强制性工作演示:http://jsfiddle.net/WB6Ty/
关于css - 防止在父 Div 上触发 Div 的悬停事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10364511/