javascript或jquery中的nth-child等价物

时间:2015-11-03 00:16:27

标签: javascript jquery css css-selectors

目前我的问题只是css中的nth-child在Google Chrome上表现得很慢。

所以我想在另一个选项中编写此代码,例如javascript / jquery或其他语言,以完全相同。

div.testbox:nth-child(4n+6) {
margin-left : 0px;
margin-right : 1%;
}
div.testbox:nth-child(4n+3) {
margin-left : 0px;
margin-right : 0px;
}

感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

这是jQuery等价物,

示例:

选择作为其父级的第三个子级的每个<p>元素:

$("p:nth-child(3)")

语法:

:nth-child(n|even|odd|formula)

或使用eq();

选择第二个<p>元素:

$("p:eq(1)")

Syantax:

$(":eq(index)")

我会使用jQuery,它与CSS的语法几乎完全相同。

答案 1 :(得分:0)

它的语法基本相同。我已经制作了jsfiddle来显示结果。

$("div.testbox:nth-child(4n+6)").css('background-color', "#333");
$("div.testbox:nth-child(4n+3)").css('background-color', "#eee");

答案 2 :(得分:0)

以下是@Victory答案的纯JavaScript版本:

https://jsfiddle.net/ryanpcmcquen/c7m16z5h/

Array.prototype.slice.call(document.querySelectorAll("div.testbox:nth-child(4n+6)")).map(function(i) {
    i.style.backgroundColor = "#333";
});
Array.prototype.slice.call(document.querySelectorAll("div.testbox:nth-child(4n+3)")).map(function(i) {
    i.style.backgroundColor = "#eee";
});
div.testbox:nth-child(4n+6) {
    color: red;
}
div.testbox:nth-child(4n+3) {
    color: blue;
}
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>
<div class="testbox">here is some text</div>

更好的是,如果要反复使用它,请将其作为一项功能:

(function (win) {
    win.styleChange = function (selectors, styleProp, styleValue) {
        Array.prototype.slice.call(document.querySelectorAll(selectors)).map(function (i) {
            i.style[styleProp] = styleValue;
        });
    };
}(window));
styleChange("div.testbox:nth-child(4n+6)", "backgroundColor", "#333");
styleChange("div.testbox:nth-child(4n+3)", "backgroundColor", "#eee");

https://jsfiddle.net/ryanpcmcquen/pL7Ln3dz/