CSS 如何在视图生成的列表中的最后一个 <li> 上添加“最后一个”类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/113702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 19:57:39  来源:igfitidea点击:

How do I add a "last" class on the last <li> within a Views-generated list?

cssdrupal

提问by user20273

How do I add a "last" class on the last <li>within a Views-generated list?

如何<li>在视图生成的列表中的最后一个添加“最后一个”类?

回答by Tim C

You could use the last-childpseudo-class on the li element to achieve this

您可以在 li 元素上使用last-child伪类来实现此目的

<html>
<head>
<style type="text/css">
ul li:last-child
{
font-weight:bold
}
</style>
</head>
<body>
<ul>
<li>IE</li>
<li>Firefox</li>
<li>Safari</li>
</ul>
</body>
</html>

There is also a first-child pseudo class available.

还有一个可用的 first-child 伪类。

I am not sure the last-child element works in IE though.

我不确定 last-child 元素在 IE 中是否有效。

回答by Tim C

Alternatively, you could achieve this via JavaScript if certain browsers don't support the last-child class. For example, this script sets the class name for the last 'li' element in all 'ul' tags, although it could easily be adapted for other tags, or specific elements.

或者,如果某些浏览器不支持 last-child 类,您可以通过 JavaScript 实现这一点。例如,此脚本为所有 'ul' 标签中的最后一个 'li' 元素设置类名,尽管它可以很容易地适用于其他标签或特定元素。

function highlightLastLI()
{
    var liList, ulTag, liTag;
    var ulList = document.getElementsByTagName("ul");
    for (var i = 0; i < ulList.length; i++)
    {
        ulTag = ulList[i];
        liList = ulTag.getElementsByTagName("li");
        liTag = liList[liList.length - 1];
        liTag.className = "lastchild";
    }
}

回答by Ajay Gupta

You can use that pesudo-class last-child, first-childfor first or nth-childfor any number of child

您可以使用该伪类last-childfirst-child为 first 或nth-child为任意数量的孩子

li:last-child{
    color:red;
    font-weight:bold;
}

回答by redsquare

Does jquery come bundled with drupal, if so you could use

jquery 是否与 drupal 捆绑在一起,如果是这样,您可以使用

$('ul>li:last').addClass('last');

to achieve this

为达到这个