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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更改最后一个 <li> 的 CSS


- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01