当鼠标悬停时更改父级div的背景

10

我有这段代码:

<div class="thumb_image_holder_orange">
    <img src="http://dummyimage.com/114x64/000/fff.png" />
</div>

图片在div中间居中,我如何在悬停在图片上时更改div的背景?

我只知道当鼠标悬停在div上时如何更改图片属性。

最好不要使用jQuery,但也不介意。

谢谢!


刚刚编辑了我的问题,虽然不太想这样做,但是因为页面上已经有jQuery了,所以也不是世界末日。 - 472084
1
很遗憾CSS中没有父级选择器。(https://dev59.com/f3VD5IYBdhLWcg3wO5AD)。如果使用jQuery不是问题,我发布的链接可能是重复的。 - Kevin
@ shakti 是的,JS 的答案是可以接受的。 - Pradeep Singh
6个回答

13

接受该能力还可以去除背景,这一点我忘了提到。谢谢。 - 472084
不用谢。我猜你想要这样做是因为你最初想要CSS中:hover的功能。 - thirtydot

5

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

您标记为,因此这里是jQuery的答案。

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

3
解决方案:解决方案是使用绝对定位。请参见下面的代码片段。 在 "orangeImg" 中添加一个 ID 将使生活变得更容易!

创建一个相对定位的容器 div,在其中放置您的 "orangeImg" 和 "orangeBG" div。两者都将具有绝对位置。由于 orangeBG div 不包含任何元素,因此还需要为其指定宽度和高度属性。使用 z-index 属性可以叠加 div,使 Img div 位于顶部。

向 orangeBG div 添加 .target 类,然后使用兄弟选择器 "~" 来选择悬停在 orangeImg div 上的任何兄弟。这里的唯一兄弟是 orangeBG div。因此,只有在悬停在图像上时才会更改背景! JSfiddle here

祝你好运,

阿兰

#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;}
<div id="holder">
  <div id="orangeImg" class="thumb_image_holder_orange">
    <img src="http://dummyimage.com/114x64/000/fff.png" />
  </div>
  <div id="orangeBG" class="target">
  </div>
  
</div><!-- end holder -->


2

在CSS中无法做到这一点。

那么使用标准JavaScript,而不是JQuery呢?

<div class="thumb_image_holder_orange">
    <img src="http://dummyimage.com/114x64/000/fff.png" onmouseover="this.parentNode.style.backgroundColor = '#f00'" onmouseout="this.parentNode.style.backgroundColor = '#fff'" />
</div>

2
以下代码片段可以完成此任务:
$('.thumb_image_holder_orange > img').hover(function() {
    $(this).parent().css('background-color', '#f00');
});

1
如果您可以在图像旁边添加一个虚拟元素,那么可以使用this pure CSS2 trick来实现,结果为this example fiddle
标记:
<div class="thumb_image_holder_orange">
    <div></div>
    <img src="http://dummyimage.com/114x64/000/fff.png" />
</div>

样式表:

.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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接