How to test for nth-child using Modernizr?

纵然是瞬间 提交于 2019-12-12 09:35:45

问题


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!


回答1:


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

Usage:

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

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

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

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




回答2:


I remember there was a Modernizr selectors plugin that tested for selectors support, but I can't find it right now. You can take a look at this: http://javascript.nwbox.com/CSSSupport/ which is similar.




回答3:


You can also use Selectivizr to add CSS3 selector support to unsupported browsers




回答4:


Mohsen, thank you for your decision. If someone needs to 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;

};


来源:https://stackoverflow.com/questions/7630408/how-to-test-for-nth-child-using-modernizr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!