2011-10-03 22 views
9

我試圖使用modernizr來測試:nth-child瀏覽器的支持,但我不知道該怎麼做,我發現這一個http://jsfiddle.net/laustdeleuran/3rEVe/哪個測試:last-child,但我不知道如何改變它來檢測:nth-child(我也考慮使用它像,因爲我相信,那些不支持:last-child瀏覽器不支持:nth-child要麼,但我不知道)如何使用Modernizr測試第n個孩子?

你們能幫助我嗎?提前致謝!

+2

說實話,這是非常合理的假設,一個瀏覽器或者支持':第n個孩子()'和':最後child',或不要麼支持。 – BoltClock

+0

試試這個插件.. http://selectivizr.com/
只在css文件下插入! – 2012-07-09 05:39:55

回答

13

我只是寫了一個函數來檢測:對第n個孩子的支持,你

function isNthChildSupported(){ 
var result = false, 
    test = document.createElement('ul'), 
    style = document.createElement('style'); 
test.setAttribute('id', 'nth-child-test'); 
style.setAttribute('type', 'text/css'); 
style.setAttribute('rel', 'stylesheet'); 
style.setAttribute('id', 'nth-child-test-style'); 
style.innerHTML = "#nth-child-test li:nth-child(even){height:10px;}"; 
for(var i=0; i<3; i++){ 
    test.appendChild(document.createElement('li')); 
} 
document.body.appendChild(test); 
document.head.appendChild(style); 
    if(document.getElementById('nth-child-test').getElementsByTagName('li')[1].offsetHeight == 10) {result = true;} 
document.body.removeChild(document.getElementById('nth-child-test')); 
document.head.removeChild(document.getElementById('nth-child-test-style')); 
    return result; 
} 

用法:

isNthChildSupported() ? console.log('yes nth child is supported') : console.log('no nth child is NOT supported'); 

你可以看到這個在這裏工作的行動 http://jsbin.com/epuxus/15

而且jQuery :nth-child和​​之間有區別。

的jQuery :nth-child支持jQuery的支持,但CSS任何瀏覽器:nth-childis supported在IE9,Chrome瀏覽器,Safari和Firefox

+3

感謝您的回答,它確實有效,但是在多看了一會之後,我發現這個實際上測試了所有選擇器的https://gist.github.com/441842,希望有人會發現它也很有用。 – javiervd

+1

我知道這是舊的,但有沒有其他人在使用此功能時在IE8中收到錯誤?見http://stackoverflow.com/questions/6631871/modifying-the-innerhtml-of-a-style-element-in-ie8 – doubleswirve

2

您還可以使用Selectivizr到CSS3選擇器支持添加到瀏覽器不受支持

+0

這很好。 – hellojebus

1

穆赫辛,謝謝你的決定。 如果有人需要的jQuery:

function test(){ 

    var result = false, 
     test = $('<ul id="nth-child-test"><li/><li/><li/></ul>').appendTo($('body')), 
     style = $('<style type="text/css">#nth-child-test li:nth-child(even){height:10px;}</style>').appendTo($('head')); 

    if(test.children('li').eq(1).height() == 10) 
    result = true; 

    test.remove(); 
    style.remove(); 

    return result; 

}; 
+0

就像一個魅力 – Alex