简体   繁体   English

如何将悬停属性与不在父级中的其他元素一起使用

[英]How to use the hover property with other elements that aren't in the parent

What I'm trying to do is get image B to appear when image A is hovered over. 我想做的是将图像A悬停在图像B上。

Here's the hover properties I'm using img.a:hover img.b {opacity:1;} 这是我正在使用img.a:hover img.b {opacity:1;}的悬停属性

The problem is.. these elements aren't in the same parent. 问题是..这些元素不在同一个父对象中。 Here's a jsfiddle. 这是一个jsfiddle。 http://jsfiddle.net/LquGC/ http://jsfiddle.net/LquGC/

I understand that it's not in the same parent but I don't understand why CSS was designed this way. 我知道它不在同一个父级中,但是我不明白为什么CSS是用这种方式设计的。 Does anybody know any workarounds for this? 有人知道任何解决方法吗?

Unfortunately CSS will only effect siblings or children. 不幸的是CSS只会影响兄弟姐妹或孩子。 It can't navigate to its parent's sibling. 它无法导航到其父级的同级。 So there is no pure CSS fix for this. 因此,没有针对此的纯CSS修复程序。

Here are two ways that may work for you. 这有两种对您有用的方法。 You can keep your current HTML and use JS to make the hover work, or change your HTML and use CSS hover states. 您可以保留当前的HTML并使用JS来使悬停工作,或者更改HTML并使用CSS悬停状态。

HTML reorder fiddle: HTML重新排序小提琴:

HTML: HTML:

 <div class="wrapper">
    <div class="group1">
         <img class="a" src="http://imgur.com/Y7Cz2Q3.jpg">
         <img class="b" src="http://imgur.com/MMZwSdO.jpg">             
    </div>
    <div class="group2">
         <img class="c" src="http://imgur.com/HHbpx0w.jpg">
         <img class="d" src="http://imgur.com/Q9LfCwH.jpg">     
    </div>
</div>

CSS: CSS:

.b, .d {
    opacity:0;
    transition: .3s;
    }
img {display: block;}   
.wrapper > div {display: inline-block;}

.group1:hover .b {
    opacity:1;
}

.group2:hover img.d {
    opacity:1;
}

JQUERY fiddle: JQUERY提琴:

JS: JS:

$('.a').hover(
    function () {
        $('.b').css('opacity','1');
    }, function () {
        $('.b').css('opacity','0');
});
$('.c').hover(
    function () {
        $('.d').css('opacity','1');
    }, function () {
        $('.d').css('opacity','0');
});

CSS: CSS:

.b,.d {
    opacity: 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM