美文网首页
css的一个伪类,nth-child

css的一个伪类,nth-child

作者: 剑来___ | 来源:发表于2018-12-20 15:11 被阅读9次

    之前在写移动端的项目的时候,对一些列表元素有一些需求
    比如,你想要给列表里的前三个元素加上边框,后三个元素变灰....我以前的做法是用js在遍历数组的时候判断当前元素的index,然后用index做一些逻辑判断操作,来给这个元素加上想要的className,这样的做法需要做很多的js计算,频繁地去使用map函数和forEach函数,并要写很多的回调函数。
    最近在看css权威指南,看到nth-child,他是一个伪类选择器,可以轻松地选取你想要的标签并给与修改添加样式(但是不支持低版本的IE!)

    1. :nth-child(2)选取第几个标签,“2可以是你想要的数字”
    .demo01 li:nth-child(2){background:#090}
    
    1. nth-child(n+4)选取大于等于4标签,nth-child(-n+4)选取小于等于4标签,“n”表示从整数
    .demo01 li:nth-child(n+4){background:#090}
    .demo01 li:nth-child(-n+4){background:#090}
    
    1. :nth-child(2n)选取偶数标签,nth-child(2n-1)选择奇数标签
    .demo01 li:nth-child(2n-1){background:#090}
    .demo01 li:nth-child(2n){background:#090}
    
    1. :nth-child(3n+1)自定义选取标签,3n+1表示“隔二取一”
    .demo01 li:nth-child(3n+1){background:#090}
    

    这样的话,也就是说你想得到该有的函数,就可以模拟出js的逻辑判断操作。

    同样的伪类选择器

    • nth-last-child() : 选择倒数第几个标签
    • last-child选取最后一个标签

    相关文章

      网友评论

          本文标题:css的一个伪类,nth-child

          本文链接:https://www.haomeiwen.com/subject/svpykqtx.html