CSS3 方式 (IE9+)
如果您确切知道最后一项的深度,您可以重复调用:last-child
:
li:last-child li:last-child {
color: red;
}
根据http://caniuse.com/#search=last-child,在 9 版之前的 IE 中不支持这种伪类选择器。当然,如果你不知道这个列表项有多深,那么这种方法并没有真正的帮助。
The JavaScript Way
You can target the very last list item via JavaScript as well:
var items = document.getElementById("mylist").getElementsByTagName("li"),
_item = items[ items.length - 1 ];
_item.className == ""
? _item.className = "last"
: _item.className += " last" ;
This is raw JavaScript, which requires no additional frameworks or libraries. If you're using a popular framework like jQuery, this could be even simpler:
$("#mylist li:last").addClass("last");
I wouldn't suggest you use jQuery just for something like this. Raw JavaScript would be far faster, and far less bloat.
The Preprocessor way
Depending on how your navigational menu is constructed, you may be able to use a server-side language to identify the last list-item, and mark it as such. For example, we could perform the following using the DOMDocument
class in PHP:
$d = new DOMDocument();
$d->loadHTML( $html );
$a = $d->getElementsByTagName("li");
$l = $a->item( $a->length - 1 );
$c = $l->getAttribute("class");
empty( $c )
? $l->setAttribute("class", "last")
: $l->setAttribute("class", "last $c");
echo $d->saveHTML( $l );
This finds the last list item in the HTML and adds a new class of "last" to it. The benefit to this is that it doesn't require complicated, and often times poorly-supported, CSS3 selectors. Further, it doesn't require the addition of large JavaScript libraries to do trivial things.