如何使用Modernizr测试第n个孩子? [英] How to test for nth-child using Modernizr?

查看:119
本文介绍了如何使用Modernizr测试第n个孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用modernizr来测试:nth-​​child 浏览器支持,但我不知道该怎么做,我发现这个 http://jsfiddle.net/laustdeleuran/3rEVe/ 测试:last-child 但我不知道如何改变它来检测:nth-​​child (我也在考虑使用它,因为我相信不支持:last-child 的浏览器不支持:nth-​​child 肯定)

I'm trying to use modernizr to test for :nth-child browser support but I'm not sure how to do it, I found this one http://jsfiddle.net/laustdeleuran/3rEVe/ which tests for :last-child but I don't know how to change it to detect :nth-child (I was also thinking about using it like that since I believe that browsers that don't support :last-child don't support :nth-child either but I'm not sure)

你们能帮助我吗?提前感谢!

Can you guys help me? Thanks in advance!

推荐答案

我刚刚写了一个函数来检测:nth-​​child支持

I just wrote a function to detect the :nth-child support for you

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

You can see this works in action here http://jsbin.com/epuxus/15

此外, jQuery :nth-​​child CSS :nth-​​child

Also There is a difference between jQuery :nth-child and CSS :nth-child.

jQuery :nth-​​child 支持但支持CSS :nth-​​child < a>在IE9,Chrome,Safari和Firefox

jQuery :nth-child is supported in any browser jQuery supports but CSS :nth-child is supported in IE9, Chrome, Safari and Firefox

这篇关于如何使用Modernizr测试第n个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆