悬停时选择先前的兄弟姐妹 [英] Select previous siblings on hover
问题描述
我有一个div里面有两个图片。当用户将鼠标悬停在第二个图像上时,第一个图像的透明度应该达到40%。我的问题是,当 img.second
被悬停在上面时,我不能选择 img.first
我已经尝试调查一般的同级选择器,但似乎只选择在你的初始选择器之后的元素。
I have two images inside a div. When the user hovers over the second image, the first one's opacity should go to 40%. I problem is that I cannot select img.first
when img.second
is being hovered over. I have tried looking into the general sibling selector, but that seems to only select the elements that come after your initial selector.
我知道这可以用jQuery,但是我想知道是否有一个纯CSS解决方案?
I know this can be done with jQuery, but I'm wondering if there is a pure CSS solution?
<div>
<img class="first" src="#">
<img class="second" src="#">
</div>
div > img.second:hover ~ img.first { opacity:0.4; filter:alpha(opacity=40); } //failed
推荐答案
我试着调查一般的同级选择器,但是似乎只选择在你的初始选择器之后的元素。
I have tried looking into the general sibling selector, but that seems to only select the elements that come after your initial selector.
正确。因此,使用纯CSS选择器是不可能的。
That is correct. As such, with a pure CSS selector this isn't possible.
但是,根据您的布局,您可以使用多个规则与选择器,如 div:hover
和 img:hover
并使用不透明度值来获得所需的内容;看到其他答案的例子。但如果你想要一个更加万无一失的解决方案,你会更好的jQuery。
However, depending on your layout, you may be able to use multiple rules with selectors such as div:hover
and img:hover
and play with opacity values to get at what you want; see the other answers for examples. But if you want a more foolproof solution you'll be better off with jQuery.
这篇关于悬停时选择先前的兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!