我理解'邻近选择器'+
我想要做的是根据div两侧的类来改变元素的样式。例如:
<div class="positive">...</div>
<div class="divider"></div>
<div class="negative">...</div>
'正'和'负'类具有不同的背景,并且分配可能会根据用户交互等进行更改。我希望div.divider根据其两侧的div类选择背景。我们有从“正 - 负”,“负到正”,“pos-to-pos”,“neg-to-neg”等“过渡”的分隔符。还有更多的状态,这些仅仅是示例。
这个想法是当JS更改div.divider两侧的div类时我想要更改分隔符的样式(主要是背景)。
这可能吗?
答案 0 :(得分:8)
CSS没有,也没有(我不认为),有一个BETWEEN选择器。浏览器将网页作为流处理,而两者之间的选择器需要引用先前读取的元素,从而减慢了渲染时间。 This页面有关于令人垂涎的parent
选择器的说明,该选择器也适用于between
选择器。
仅将中间div用作样式元素在语义上不合适,以下可能是更好的选择。
我认为您最好的选择是使用ADJACENT选择器更改positive
或negative
的上半部分以响应其邻居。使用CSS3:
.positive + .negative { border-top-image:url('NEGATIVE_BELOW_POSTIIVE'); }
.negative + .positive { border-top-image:url('POSITIVE_BELOW_NEGATIVE'); }
您还可以在CSS3中使用多个背景图像:
.positive + .negative { background-image:url('NEGATIVE_BELOW_POSTIIVE');
background-position:center-top;
}
.negative + .positive { background-image:url('POSITIVE_BELOW_NEGATIVE');
background-position:center-top;
}
在CSS2及更早版本中,您可能需要预先构建所有背景图像并使用上述策略进行更改。
.positive, .negative { background-image:url('DEFAULT'); }
.positive + .negative { background-image:url('NEGATIVE_BELOW_POSTIIVE'); }
.negative + .positive { background-image:url('POSITIVE_BELOW_NEGATIVE'); }