Changing CSS for last lt;ligt;(更改最后一个 lt;ligt; 的 CSS)
问题描述
我想知道是否有某种方法可以使用 CSS 更改列表中最后一个 li
的 CSS 属性.我已经研究过使用 :last-child
,但这似乎真的有问题,我无法让它为我工作.如有必要,我将使用 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 中有一个 lastChild
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.
这是一个在原型中做你想做的事的例子:
Here's an example of doing what you want in Prototype:
$$("ul").each(function(x) { $(x.lastChild).addClassName("last-item"); });
或者更简单:
$$("ul li:last-child").each(function(x) { x.addClassName("last-item"); });
在jQuery中,你可以写得更简洁:
In jQuery, you can write it even more compactly:
$("ul li:last-child").addClass("last-item");
还要注意,这个应该在不使用实际的 last-child
CSS 选择器的情况下工作 - 而是使用它的 JavaScript 实现 - 所以它应该更少错误并且跨浏览器更可靠.
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.
这篇关于更改最后一个 <li> 的 CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!