处理css中“li”的第一个或最后一个样式

这个题目真心难取啊,估计仅仅看题目是难以理解的文章写的什么,所以仔细阅读吧,上图为大家驾驶一番

enter image description here

就是为了处理掉上图所标注的最后一个li样式,所以这篇文章应运而生,其实这个问题早在当初折腾代码实现文章仿“无觅”效果的 相关文章的时候便产生了,当初没怎么在意,直到阅读到 @倡萌 的文章后,问题解决了,倡萌那里提供了两种解决办法,都是用的js,但是我并不喜欢这两种方式,于是尝试纯CSS方式。

下面的前两种方法是来自倡萌提供的的JS代码,优点是兼容性好支持低版本的IE6浏览器,不过现在使用IE6的用户真的是越来越少了,你可以大胆的采用CSS的方式来完成这一操作,那就看一看“方法三”

方法一

已经引入了jQuery库,再加一句简单的js代码即可:

<html>
<title></title>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>//引入jQuery库
<script type="text/javascript">
$(function(){
$("#test li:last").css("border","none");//关键函数,注意容器id“#test”要和html代码中一样
})
</script>
<style type="text/css">
ul,li{ margin:0; padding:0; list-style:none; }
#test{ width:200px;}
#test li{ width:100%; height:24px; border-right:1px solid red;}
</style>
</head>
<body>
<ul id="test">
<li>菜单一</li>
<li>菜单二</li>
<li>菜单三</li>
</ul>
</body>
</html>

方法二

没有引入jQuery库,使用原生js代码实现:

<html>
<title></title>
<head>
<script type="text/javascript">
window.onload = function urlborder() {
        var listr = document.getElementById("test").getElementsByTagName('li'); //注意容器id“test”要和html代码中一样
        for (var i = 0; i < listr.length; i++) {
            if (i == listr.length - 1) {
                listr[i].style.borderWidth = "0";
            }
        }
    }
</script>
<style type="text/css">
ul,li{ margin:0; padding:0; list-style:none; }
#test{ width:200px;}
#test li{ width:100%; height:24px; border-right:1px solid red;}
</style>
</head>
<body>
<ul id="test">
<li>菜单一</li>
<li>菜单二</li>
<li>菜单三</li>
</ul>
</body>
</html>

方法三

使用:first-child:last-child伪类:

纯css的:first-child:last-child伪类就可以胜任此任务,操作很方便,代码量忽略不计。支持IE7+,不支持IE6(last支持IE8+)

以兼容性更好的:first-child伪类为例,关于:first-child伪类的解释如下:

:first-child 伪类向元素的第一个子元素添加样式。

阅读详细解释 >

处理前,需要把li样式的right线改为left:

enter image description here

参考代码:

.relatebar li{width:98px;height:146px;padding:5px;float:left;border-left:1px solid #ccc;}
.relatebar li:first-child{border-left:0px solid #ccc;}

解释:

用:first-child伪类给li的第一个样式改为0px,或者none也行,这样第一个li就没有哪条多余的横线啦!

:last-child伪类与:first-child伪类用法相同,不同的是:last-child是为元素的最后一个子元素添加样式

Tokin
Tokin
Wandering in Shanghai.