如何使用 Modernizr 测试第 n 个孩子?

2024-02-08

我正在尝试使用 Modernizr 来测试:nth-child浏览器支持,但我不知道该怎么做,我找到了这个http://jsfiddle.net/laustdeleuran/3rEVe/ 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;
}

Usage:

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

你可以在这里看到它的实际效果http://jsbin.com/epuxus/15 http://jsbin.com/epuxus/15

之间也有区别jQuery :nth-child http://api.jquery.com/nth-child-selector/ and CSS :nth-child https://developer.mozilla.org/en/CSS/:nth-child.

jQuery :nth-child is任何浏览器都支持 jQuery 支持,但 CSS 除外:nth-child 支持 http://caniuse.com/#search=nth-child在 IE9、Chrome、Safari 和 Firefox 中

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Modernizr 测试第 n 个孩子? 的相关文章

随机推荐