CSS只改变一个单独的div颜色悬停,即使不是嵌套或兄弟? [英] CSS only change a separate div color on hover even if not nested or sibling?
问题描述
我有两个div:
< div&
< a id =changecolor>更改颜色< / a>
< / div>
< div id =tobechanged>
更改我的颜色
< / div>
我有两个问题:
- 我如何使用CSS,以便当我悬停在#changecolor上时,
#tobechanged
的背景颜色会发生变化? - 有一种方法,只使用
CSS3
,这样点击changecolor将触发CSS颜色更改,而不是悬停? li>
以下是我尝试的:
#changecolor:hover + #tobechanged {
background:yellow;
}
这只有在我有这样的东西时才有效:
< div>
< a id =changecolor>更改颜色< / a>
< div id =tobechanged>
更改我的颜色
< / div>
< / div>
但我不想让tobechanged成为changecolor的兄弟姐妹或孩子。 / p>
我找到了您的第一个div:
< div&
< a id =changecolor>更改颜色< / a>
< / div>
< div id =tobechanged>
更改我的颜色
< / div>
没有ID名称,更改为:
< div id =mycolor>
< a id =changecolor>更改颜色< / a>
< / div>
< div id =tobechanged>
更改我的颜色
< / div>
而CSS为:
#mycolor:hover + #tobechanged {
background:yellow;
}
我可以更改它。
但我不确定您是否要在 div:hover
或上更改颜色:hover
(通过ID调用它们),所以如果你想要 a:hover
:
然后,不需要有包含< a>
元素的第一个div,因此HTML可能是这样:
< a id =changecolor>更改颜色< / a>
< div id =tobechanged>
更改我的颜色
< / div>
和CSS like:
#changecolor:hover + #tobechanged {
background:yellow;
}
$ b
对于您的第二个问题 @ Maverick 为您提供了答案或有用的链接
I have two divs:
<div>
<a id="changecolor">Change Color</a>
</div>
<div id="tobechanged">
Change My Color
</div>
I have two questions:
- How can I use CSS only to make it so that the background color of
#tobechanged
changes when I hover on "#changecolor"? - Is there a way, using only
CSS3
, such that clicking on "changecolor" would trigger the CSS color change instead of an on hover?
The following is what I tried:
#changecolor:hover + #tobechanged {
background:yellow;
}
This works only when I have something like this:
<div>
<a id="changecolor">Change Color</a>
<div id="tobechanged">
Change My Color
</div>
</div>
But I do not want to have "tobechanged" be a sibling or child of "changecolor".
Ok after checking your code again and looking at this topic
I found your 1st div:
<div>
<a id="changecolor">Change Color</a>
</div>
<div id="tobechanged">
Change My Color
</div>
had no id name, after changing that with:
<div id = "mycolor">
<a id="changecolor">Change Color</a>
</div>
<div id="tobechanged">
Change My Color
</div>
And the CSS as:
#mycolor:hover + #tobechanged {
background:yellow;
}
I was able to change it.
BUT I'm not sure if you want to change color on div:hover
or a:hover
(calling them by ID) so if you want it on a:hover
:
Then there's no need to have the 1st div containing <a>
element so HTML could be like this:
<a id="changecolor">Change Color</a>
<div id="tobechanged">
Change My Color
</div>
and CSS like:
#changecolor:hover + #tobechanged {
background:yellow;
}
Look for this for mycolor:hover
fiddle and this for changecolor:hover
Hope this helps
And for your 2nd question @Maverick gave you the answer or a usefull link
这篇关于CSS只改变一个单独的div颜色悬停,即使不是嵌套或兄弟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!