上一个相邻的同级选择器变通办法? [英] Previous adjacent sibling selector workaround?

查看:85
本文介绍了上一个相邻的同级选择器变通办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相邻的选择器,当它们悬停在另一个选择器上时,我会想要实现.在下面的示例中,两个选择器在悬停时应会影响其他CSS.当将鼠标悬停在.a上时,此方法可以完美地工作,但是将鼠标悬停在.b上时,该方法将无法正常工作.我意识到这是因为DOM是按顺序读取的,因此CSS选择器无法向后工作.

I have two adjacent selectors that I would like to effect when hovering over the other. In the example below, the two selectors should effect the others CSS when hovered. This works perfectly when hovering .a, but not when hovering .b. I realize this is because the DOM is read in order, and therefore CSS selectors cannot work backwards.

但是,是否有可以实现此效果的jQuery解决方法(或任何其他建议)?

However, is there a jQuery workaround (or any other suggestions) that can achieve this effect?

这是小提琴

谢谢.

HTML

<figure>
    <div class="a">
        A
    </div>
    <div class="b">
        B
    </div>
</figure>

CSS

.a {
    width: 100px;
    height: 100px;
    background: red;
}

.b {
    width: 100px;
    height: 100px;
    background: blue;
}

.a:hover ~ .b {
    background: green;
}

.b:hover ~ .a { /* This one doesn't work */
    background: green;
}

推荐答案

css中没有先前的选择器.一种方法是像@Alex Char所指出的那样使用jQuery实现它,另一种方法是将鼠标悬停在父项上,而不是使用纯CSS这样的实际项:

There's no previous selector in css. One way is to implement it wiht jQuery like @Alex Char pointed out, and other way is with hover on parent, instead the actual items, with pure css like this:

.a {
    width: 100px;
    height: 100px;
    background: red;
}
.b {
    width: 100px;
    height: 100px;
    background: blue;
}

.parent{             /* ADDED */
    width: 100px;
}

.parent:hover > div:not(:hover) {   /* ADDED */
    background: green;
}

<figure class='parent'>
    <div class="a">
        A
    </div>
    <div class="b">
        B
    </div>
</figure>

这篇关于上一个相邻的同级选择器变通办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆