문제

jsfiddle

How can I simplify these nthchild selectors:

body {
    width:1012px;
}

div {
    width:1em;
    height:1em;
    float:left;
}

div:nth-child(10n+1),
div:nth-child(10n+4),
div:nth-child(10n+5),
div:nth-child(10n+6),
div:nth-child(10n+8) {
    background:#3498db;
    border:1px solid #ecf0f1;
}
div:nth-child(10n+2),
div:nth-child(10n+3),
div:nth-child(10n+7),
div:nth-child(10n+9),
div:nth-child(10n+10) {
    background:#ecf0f1;
    border:1px solid #3498db;
}

jQuery

for (var i = 0; i < 1000; i++) {
    $('body').prepend('<div></div>');
}

I appened 1000 div elements to the body. How is it possible to shorten the nth-child selectors? Or.. can I use jquery to replace the nthchild selectors? Anything that makes it readable would be very nice.

Thanks in advance!!!

도움이 되었습니까?

해결책

You can always simplify your selectors like this:

http://jsfiddle.net/VK6kE/2/

div {
    width:1em;height:1em;
    float:left;
    background:#ecf0f1;
    border:1px solid #3498db;
}
div:nth-child(10n+1), div:nth-child(10n+4), div:nth-child(10n+5), div:nth-child(10n+6), div:nth-child(10n+8) {
    background:#3498db;
    border:1px solid #ecf0f1;
}
body {width:1012px;}

What I did was:

  • set the white-ish style as the default
  • let the others override this style

This way you can eliminate 5 selectors without increasing code.

Also as posted by another user in comments (nicolallias) and as per the OP request, I will also add the way to shorten it with more javascript code:

for(var i = 0; i < 1000; i++){
    switch(i%10){
        case 1:
        case 4:
        case 5:
        case 6:
        case 8:
            $('body').prepend('<div class="one"></div>'); break;
        case 2:
        case 3:
        case 7:
        case 9:
        case 0:
            $('body').prepend('<div class="two"></div>'); break;
    }
}

.one {
    background:#3498db;
    border:1px solid #ecf0f1;
}
.two {
    background:#ecf0f1;
    border:1px solid #3498db;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top