2013-05-09 59 views
1

我使用JavaScript/jQuery来检测浏览器是否支持nth-of-type CSS3伪类。在CSS中分配5px padding-left(请参阅下面的代码),如果JS/jQ可以通过$(document).ready()读取它,则检测成功。为什么nth-type检测只能在Firefox中失败?

对于Chrome 26,IE9,Win Safari 5.1和Opera 12,所有这些都检测到5px设置,一切正常。但是,确实支持nth-of-type的Firefox 20显示padding-left设置为0px,因此测试失败。为什么nth-of-type检测仅在Firefox中失败?

示例代码。 (从我的生产代码精简。如果你想用它做实验,这也是可在http://jsfiddle.net/jma7777/ZnzBN/1/打开控制台看到padding-left检测结果。)

<!DOCTYPE html> 
<html lang="en-us"> 
<head> 
<meta charset="UTF-8"> 
<title>Pseudo Class Nth-of-Type Detector</title> 
<style> 
#checkPsdoClass1 tr.rows:nth-of-type(odd) { 
    padding-left: 5px; 
} 
</style> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script> 
$(document).ready(function() { 
    // Checks for style assigned to :nth-of-type(odd) 
    if ($('#checkPsdoClass2').css('padding-left') !== '5px') { 
    $('#pseudoClassDemo').html('<p>Your browser does not support the <code>:nth-of-type</code> pseudo-class.'); 
    } 
    console.log($('#checkPsdoClass2').css('padding-left')); // Modern browsers log 5px except Firefox which logs 0px 
    console.log($('#checkPsdoClass1 tr.rows:nth-of-type(odd)').css('padding-left')); // Modern browsers log 5px except Firefox which logs 0px 
    console.log($('tr.rows:nth-of-type(odd)').css('padding-left')); // Modern browsers log 5px except Firefox which logs 0px 
}); 
</script> 
</head> 

<body> 
<table id="checkPsdoClass1"><tr id="checkPsdoClass2" class="rows"><td><p id="checkPdsoElmnt">This table is used to test if the browser supports the nth-of-type pseudo-class.</p></td></tr></table> 
</body> 

</html> 
+0

我不知道,这是关系到你的问题,但请记住,jQuery的不支持'n次的类型“直到版本”1.9“。 – 2013-05-09 21:52:47

回答

3

我认为这个问题是Firefox不将填充应用于表格行元素;见MDN对于细节:

[填充]适用于除表列的基团,表头的基团,表英尺的基团,表行,表列组和表列中的所有元素

尝试分配填充的第一个孩子,而不是细胞:

#checkPsdoClass1 tr.rows:nth-of-type(odd) td:first-child { 
    padding-left: 5px; 
} 
+0

快速测试表明这正是问题所在。 – Mathletics 2013-05-09 22:00:58

+0

谢谢,解决了! – jma7777 2013-05-09 22:30:25