css - 如何使用 Modernizr 测试第 n 个 child ?

标签 css css-selectors modernizr

我正在尝试使用 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/

相关文章:

css - 将 modernizr 与使用多个 css3 样式的 css 类一起使用?

jquery - 为什么我的模态 Bootstrap 表单表现得像这样?

html - 当通过 :active? 触发时,IE10 是否识别兄弟组合器

html - tr 的背景色只出现在文本后面

html - 即使正确使用 modernizr,歌剧也会显示多个日期选择器

javascript - 如何使用 js 而不是自定义构建来命名 Modernizr 类?

html - 如何使这行图像在 CSS 中响应?

css - 简化具有相同父级的 css 选择器

css - 尽管使用背景图像和 Z-Index,侧边栏标题重叠

css - :nth-child() and :nth-of-type() selectors的实际使用