9

我正在尝试使用modernizr 来测试:nth-child浏览器支持,但我不知道该怎么做,我发现了这个http://jsfiddle.net/laustdeleuran/3rEVe/可以测试:last-child但我不知道怎么做更改它以检测:nth-child(我也在考虑这样使用它,因为我相信不支持的浏览器:last-child也不支持:nth-child,但我不确定)

你们能帮帮我吗?提前致谢!

4

4 回答 4

13

我刚刚写了一个函数来检测你的 :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-childCSS:nth-child之间也有区别。

:nth-child 任何浏览器都支持 jQuery jQuery支持,但IE9、Chrome、Safari 和 Firefox:nth-child 支持CSS

于 2011-10-03T01:45:09.377 回答
3

我记得有一个 Modernizr 选择器插件测试了选择器支持,但我现在找不到它。你可以看看这个:http: //javascript.nwbox.com/CSSSupport/这是类似的。

于 2011-10-03T09:42:22.437 回答
2

您还可以使用Selectivizr将 CSS3 选择器支持添加到不受支持的浏览器

于 2012-07-19T17:34:52.067 回答
1

Mohsen,谢谢你的决定。如果有人需要 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;

};
于 2014-02-21T01:17:52.767 回答