[英]CSS or JS Rule for all Divs to Change BG Color of Div inside Div, Without Changing Parent Div
I know it seems trivial, but I'm having some trouble wrapping my head around this. 我知道这似乎是微不足道的,但是我在解决这个问题时遇到了一些麻烦。
<div id="divA" style="width: 400px; height: 400px; background-color: #FF0000;">
<div id="divB" style="float: left; width: 200px; height: 200px; background-color: #FFFF00;">
<div id="divC" style="float: left; width: 100px; height: 100px; background-color: #FF00FF;">
</div>
</div>
</div>
What I need is a rule that applies to all divs, like div:hover { background-color: #000000 !important; 我需要的是一条适用于所有div的规则,例如div:hover {background-color:#000000!important; }, that only affects the first parent div of the event (when I hover divC, I want the background color of divC to change to black, but not the background colors of divB or divA)... like the inspector does in Google Chrome. },它只会影响事件的第一个父div(当我将divC悬停时,我希望divC的背景色变为黑色,而不是divB或divA的背景色)...就像检查器在Google Chrome中一样。
Any ideas? 有任何想法吗?
I don't believe it is possible to do this with just CSS, but you can with JavaScript. 我不相信仅CSS就有可能做到这一点,但是JavaScript可以做到。
The key is to use event.stopPropagation()
on the mouseover event. 关键是在mouseover事件上使用event.stopPropagation()
。
Here is an example using jQuery: http://jsfiddle.net/K96DS/2/ 这是使用jQuery的示例: http : //jsfiddle.net/K96DS/2/
$('div').on('mouseover', function(){
$(this).addClass('hovered')
// this is the key, this stops te mouover event
// from bubbling up to the parent elements
event.stopPropagation();
}).on('mouseout', function(){
$(this).removeClass('hovered')
})
Are you thinking using something like .this because of an odd behavior in :hover? 您是否正在考虑使用.this之类的东西,因为:hover行为异常?
.mouseover(function(){
$(this).addClass('selected');
});
#divC:hover #divA { background-color: #FF0000 !important; }
#divC:hover #divB { background-color: #FFFF00 !important; }
Maybe hacks... :) 也许是骇客... :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.