我想选择以下标签。这是否可以在不改变HTML
结构的情况下实现? DIV.first
元素是动态添加的,因此可能会发生变化。我需要在.first.bb
之前的每个.first.a
以及#wrapper
中已经完成的最后一个设置样式。
HTML
<div id="wrapper">
<div class="first">first</div>
<div class="first bb">first second</div>
<div class="first bb">first second</div>
<div class="first bb">first second</div> <!-- <- need to select this -->
<div class="first a">first</div>
<div class="first a">first</div>
<div class="first a">first</div>
<div class="first bb">first second</div>
<div class="first bb">first second</div>
<div class="first bb">first second</div>
<div class="first bb">first second</div> <!-- <- need to select this -->
<div class="first a">first</div>
<div class="first a">first</div>
<div class="first a">first</div>
<div class="first bb">first second</div> <!-- <- need to select this -->
</div>
CSS
.first.bb:last-child {
color:red;
}
.first.bb + .first.a {
color:red;
}
答案 0 :(得分:0)
在询问时,以前的兄弟选择器位只能使用JavaScript完成 。见http://jsfiddle.net/iamnotsam/t4BUW/
// With jQuery
$('.bb + .a').prev().addClass('last-first-bb');
或使用纯JavaScript
// With just JavaScript
var elements = document.querySelectorAll('.bb + .a'),
className = 'last-first-bb';
Array.prototype.forEach.call(elements, function(el, i){
var el = el.previousElementSibling;
if (el.classList)
el.classList.add(className);
else
el.className += ' ' + className;
});
这样可以选择问题的棘手部分。使用CSS选择#wrapper的最后一个子项是微不足道的,所以我们不需要这些技巧。