在hover时更改父div的背景

我有这个代码:

图像位于div的中间,当我将鼠标hover在图像上时,如何更改div的背景?

我只知道当我将鼠标hover在div上时如何更改图像属性。

宁愿不使用jQuery,但不要太在意。

谢谢!

你不能。 CSS无法选择“父元素”:

http://snook.ca/archives/html_and_css/css-parent-selectors

宁愿不使用jQuery,但不要太在意。

使用: http : //jsfiddle.net/KHc6X/

 $('.thumb_image_holder_orange > img').hover(function(){ $(this).parent().toggleClass('hover'); }) 

CSS选择器无法提升,因此您需要使用JavaScript。

你标记它jquery所以这是一个jQuery的答案。

 $('.thumb_image_holder_orange img').mouseover(function() { $(this).parent().css('backgroundImage', 'url(/whatever/you/want.png)'); }); 

解决方案:解决方案是使用绝对定位。 请参阅下面的代码段。 添加“orangeImg”ID会让生活变得更轻松!

创建具有相对定位的持有者div。 在这个div里面你的“orangeImg”和“orangeBG”div。 两者都有绝对定位。 orangeBG div还需要赋予width和height属性,因为它不包含任何元素。 使用z-index属性,您将对div进行分层,Img div位于顶部。

将.target类添加到orangeBG div,然后可以使用兄弟选择器“〜”,然后在hover时选择orangeImg div的任何兄弟。 这里唯一的兄弟是orangeBG div。 因此,只有当图像hover时,背景才会改变! JS在这里

祝你好运,

艾伦

 #holder {position: relative; width: 200px; height:100px;} #orangeImg {position:absolute; top:10px; right:10px; z-index:9999;} #orangeBG {position:absolute; top:0px; right:0px; z-index:1; background-color:#353;width: 200px; height:100px;} #orangeImg:hover ~ .target {background-color:#621;} 
 

以下代码片段应该完成这项工作:

 $('.thumb_image_holder_orange > img').hover(function() { $(this).parent().css('background-color', '#f00'); }); 

你不能在CSS中这样做。

标准JavaScript,而不是JQuery呢?

 

如果你可以在图像附近添加一个虚拟元素,那么这可以通过使用这个纯CSS2技巧来完成,从而导致这个例子小提琴 。

标记:

 

样式表:

 .thumb_image_holder_orange { background: orange; position: relative; } .thumb_image_holder_orange:hover { background: red; } .thumb_image_holder_orange div:hover { background: orange; } .thumb_image_holder_orange img { position: absolute; }