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
基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
