2013-05-09 29 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