【问题标题】:How to test for nth-child using Modernizr?如何使用 Modernizr 测试第 n 个孩子?
【发布时间】:2011-10-03 01:41:17
【问题描述】:

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

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

【问题讨论】:

  • 老实说,假设浏览器要么支持:nth-child() 和:last-child,要么都不支持,这是非常合理的。
  • 试试这个插件.. selectivizr.com
    只在css文件下面/之后插入!

标签: css css-selectors modernizr


【解决方案1】:

我刚刚为你写了一个函数来检测 :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 中

【讨论】:

  • 感谢您的回答,它确实有效,但在环顾四周后,我发现了这个gist.github.com/441842,它实际上测试了所有选择器,希望有人会发现它也很有用。
  • 我知道这是旧的,但其他人在使用此功能时会在 IE8 中收到错误吗?见stackoverflow.com/questions/6631871/…
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    您也可以使用Selectivizr 为不受支持的浏览器添加 CSS3 选择器支持

    【讨论】:

      【解决方案4】:

      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;
      
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-11
        • 2014-10-06
        • 2013-01-21
        • 2021-04-15
        • 2016-07-08
        • 1970-01-01
        • 2021-05-30
        相关资源
        最近更新 更多