I need to set special styles for li.done
depending on whether they are before or after li.current
. How can I do that using jQuery or CSS?
ul { list-style: none; padding: 0; margin: 0; }
ul li {
display:inline-table;
padding: 5px 12px;
color: #ddd;
background-color: #bbb;
margin: 0;
}
.done {
background-color: #ddd;
color: #aaa
}
.current {
background-color: #99f;
color: #dee
}
<ul>
<li class="done">step 1</li>
<li class="done">step 2</li>
<li class="current">step 3</li>
<li class="done">step 4</li>
<li>step 5</li>
</ul>
答案 0 :(得分:4)
You should take a look at jQuerys .prevAll()
and .nextAll()
.
var current = $(".current");
current.prevAll(".done").addClass("before");
current.nextAll(".done").addclass("after");
Please note that you will have to redo this every time you change the current element.
答案 1 :(得分:3)
You can achieve this just with CSS by using the ~
selector. From the W3 documentation:
General sibling combinator
The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.
That means that you could set the styles for the .done
that happen after .current
by applying the selector: .current ~ .done
.
One example:
ul { list-style: none; padding: 0; margin: 0; }
ul li {
display:inline-table;
padding: 5px 12px;
color: #ddd;
background-color: #bbb;
margin: 0;
}
.done {
background-color: #ddd;
color: #aaa
}
.current {
background-color: #99f;
color: #dee
}
.current ~ .done {
background-color:#f99;
color:white;
}
<ul>
<li class="done">step 1</li>
<li class="done">step 2</li>
<li class="current">step 3</li>
<li class="done">step 4</li>
<li class="done">step 5</li>
<li>step 6</li>
</ul>