CSS第n个孩子元素写法

html-css011

CSS第n个孩子元素写法,第1张

在开发中,需要这样一个需求,需要找到第n个孩子元素。一时想不起来应该怎么写,经过查阅后得知。

因此记录一下,以免日后再忘记。

:nth-child 是CSS伪类,它首先找到所有当前元素的兄弟元素,然后按照位置 先后顺序从1开始排序 ,选择的结果为CSS伪类:nth-chilid括号中表达式(an+b)匹配到的元素集合。(n=0,1,2,3)。

tr:nth-child(2n+1)

表示表格中的奇数行

tr:nth-child(odd)

表示表格汇总的奇数行

tr:nth-child(2n)

表示表格中的偶数行

tr:nth-child(even)

表示表格中的偶数行

span:nth-child(0n+1)

表示子元素中第一个且为span的元素,与:first-child选择器的作用相同

span:nth-child(-n+3)

匹配前三个子元素中的span元素

https://developer.mozilla.org/zh-CN/docs/Web/CSS/:nth-child

$(function () {

    // 保存.nav,不要每次都重新查找

    var $nav = $(".nav")

    $nav.find("li:not(:has(ul)) > a").css({

        textDecoration: "none"

    }).click(function () {

        // 不明白这里$(this).get(0).location.href是什么

        $(this).get(0).location.href = "'" + $(this).attr("href") + "'"

    })

    $nav.find("li:has(ul) > a")

        .click(function () {

            var $nextUl = $(this).next("ul")

            if ($nextUl.is(":hidden")) {

                $nextUl.slideDown("slow")

                if ($(this).parent("li").siblings("li").children("ul").is(":visible")) {

                    $(this).parent("li").siblings("li").find("ul").slideUp("1000")

                }

            } else {

                //不用toggle()的原因是为了在收缩菜单的时候同时也将该菜单的下级菜单以后的所有元素都隐藏

                $nextUl.slideUp("normal").children("li").find("ul").fadeOut("normal")

            }

            return false

        })

    /*去掉a标签边框线,适用用IE*/

    $nav.find("a").attr("hidefocus", true)

    // 这个可以拿出来

    function setCSS(el, bg, color, fontSize) {

        $(el).css({

            background: "url(../images/" + bg + ") no-repeat",

            color: color || "#000", // 默认是"#000"

            fontSize: fontSize || 12 // 默认是12

        })

    }

    $(".topMenu").mouseover(function () {

        setCSS(this, "TreeImages/bgBlue.jpg", "#fff", 14)

    }).mouseout(function () {

        if (this.className != "selectedMenu") {

            setCSS(this, "TreeImages/bg.jpg")

        }

    }).click(function () {

        $(".selectedMenu").not(this).attr("class", "")

        setCSS(this, "TreeImages/bg.jpg")

        this.className = this.className == "selectedMenu" ? "" : "selectedMenu"

    })

    $(".hasChild").css({

        color: "#000"

    }).mouseover(function () {

        $(this).css({

            fontSize: 14,

            color: "red"

        })

    }).mouseout(function () {

        setCSS(this, "collapse_arrow1.png")

    }).click(function () {})

})