CSS兄弟选择器替代方案

时间:2014-03-11 17:33:55

标签: html css selector siblings

我试图在另一个元素悬停时导致一个元素发生变化。我知道这可以使用兄弟选择器(〜)完成,但它似乎没有工作。我试图找到一个替代使用兄弟选择器,但只找到我不知道的JavaScript中的解决方案。

我认为问题可能来自这样一个事实,即我试图将多个元素绑定到一个兄弟,也就是说,悬停在3个不同的div上都会以三种不同的方式改变一个div。虽然我错了,但我觉得这不是错误,代码就在这里......

CSS

#internalContainer {
width:900px;
height:400px;
}
#sectionLeft {
float:left;
height:400px;
width:300px;
}
.leftInternal {
height:100px;
width:300px;
text-align:right;
}
#titleA {
font-size:11pt;
font-weight: bold;
text-transform: uppercase;
letter-spacing:1px;
position:relative;
top:40%;
transition:.2s
}
#sectionRight {
float:left;
width:568px;
height:400px;
margin-left:32px;
background-color:#f2f2f2;
}
#titleA:hover {
top:45%;
transition:.2s
}
#titleA:hover ~ #sectionRight {
background: #ccc;
}

HTML

<div id="internalContainer">
<div id="sectionLeft">
<div class="leftInternal"><div id="titleA">Title of One</div></div>
<div class="leftInternal"><div id="titleA">Title of Two</div></div>
<div class="leftInternal"><div id="titleA">Title of Three</div></div>
<div class="leftInternal"><div id="titleA">Title of Four</div></div>
</div>
<div id="sectionRight">
</div>
</div>

http://jsfiddle.net/xs7h8/

当链接悬停时,目前没有任何变化,但它们现在都设置为做同样的事情。我打算为titleA创建子类,并将每个子类连接到sectionRight,但这也不起作用。

1 个答案:

答案 0 :(得分:2)

您不能拥有重复的ID 。它根本行不通。这是你的问题

此外,#titleA不是#sectionRight的兄弟姐妹,因此兄弟选择器不起作用。 #sectionRight是他们的叔叔,由于目前没有父选择器,因此无法在悬停时使用CSS选择它

您也无需重复transition中的hover,它是从默认状态继承的

This is the closest you can get使用您当前的设置而不使用javascript,将悬停应用于#sectionLeft而不是