在 CSS 悬停事件中,我可以更改另一个 div 的样式吗? [英] On a CSS hover event, can I change another div's styling?

查看:20
本文介绍了在 CSS 悬停事件中,我可以更改另一个 div 的样式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将鼠标悬停在 id 为a"的 div 或类上时,是否可以更改 id 为b"的 div 或类的背景颜色?

When I hover over a div or class with an id of "a", can I get the background color of a div or class with the id of "b" to change?

推荐答案

是的,您可以这样做,但前提是 #b 在 HTML 中的 #a 之后.

Yes, you can do that, but only if #b is after #a in the HTML.

如果 #b 紧跟在 #a 之后:http://jsfiddle.net/u7tYE/

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {
    background: #ccc
}

<div id="a">Div A</div>
<div id="b">Div B</div>

这是使用相邻兄弟组合器 (+).

如果#a#b 之间还有其他元素,可以使用这个:http://jsfiddle.net/u7tYE/1/

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {
    background: #ccc
}

<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>

这是使用一般兄弟组合器(~).

+~ 都适用于所有现代浏览器和 IE7+

Both + and ~ work in all modern browsers and IE7+

如果#b#a 的后代,你可以简单地使用#a:hover #b.

If #b is a descendant of #a, you can simply use #a:hover #b.

替代方案:您可以使用纯 CSS 来完成此操作,方法是将第二个元素放在第一个元素之前.第一个 div 在标记中位于第一个,但位于第二个 div 的右侧或下方.它会像以前的兄弟姐妹一样工作.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

这篇关于在 CSS 悬停事件中,我可以更改另一个 div 的样式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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