我正在尝试使用 modernizr 来测试 :nth-child
浏览器支持,但我不确定该怎么做,我找到了这个 http://jsfiddle.net/laustdeleuran/3rEVe/哪个测试 :last-child
但我不知道如何更改它以检测 :nth-child
(我也在考虑那样使用它,因为我相信不支持 :last-child
的浏览器也不支持 :nth-child
但我不确定)
你们能帮帮我吗?提前致谢!
最佳答案
我刚刚写了一个函数来检测 :nth-child 对你的支持
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
之间也有区别和 CSS :nth-child
.
jQuery :nth-child
在 jQuery 支持的任何浏览器中都被支持,但 CSS :nth-child
is supported在 IE9、Chrome、Safari 和 Firefox 中
关于css - 如何使用 Modernizr 测试第 n 个 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7630408/