问题描述
我想知道是否有一些方法可以使用CSS更改列表中最后一个 li
的CSS属性。我已经研究使用:last-child
,但这似乎真的bug,我不能让它为我工作。如果有必要,我将使用JavaScript来执行此操作,但我想知道是否有人可以在CSS中想出一个解决方案。
I am wondering if there is some way to change a CSS attribute for the last li
in a list using CSS. I have looked into using :last-child
, but this seems really buggy and I can't get it to work for me. I will use JavaScript to do this if necessary, but I want to know if anyone can think up a solution in CSS.
推荐答案
:last-child
是唯一的方法,而不修改HTML - 但假设你可以这样做,主要选项只是给它一个 class =last-item
,然后执行:
:last-child
is really the only way to do it without modifying the HTML - but assuming you can do that, the main option is just to give it a class="last-item"
, then do:
li.last-item { /* ... */ }
显然,您可以在动态页面生成语言你的选择。此外,还有 W3C DOM中的JavaScript属性。
Obviously, you can automate this in the dynamic page generation language of your choice. Also, there is a lastChild
JavaScript property in the W3C DOM.
以下是在:
$$("ul").each(function(x) { $(x.lastChild).addClassName("last-item"); });
或更简单:
$$("ul li:last-child").each(function(x) { x.addClassName("last-item"); });
在,您可以更紧凑地写:
In jQuery, you can write it even more compactly:
$("ul li:last-child").addClass("last-item");
另请注意,此应该工作,而不使用实际 last-child
CSS选择器 - 相反,它使用的JavaScript实现 - 因此它应该更少的bug和更可靠的浏览器。
Also note that this should work without using the actual last-child
CSS selector - rather, a JavaScript implementation of it is used - so it should be less buggy and more reliable across browsers.
这篇关于更改最后的CSS< li>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!