2012-02-22 24 views
0
$(' .middle.clear > .post_home:first ').css('padding-left', '270px !important'); 

Firefox中的這段代碼從元素1開始,而Chrome從元素0開始。 我該如何對待它?Jquery firefox不當行爲

+0

你的HTML看起來像什麼? – 2012-02-22 02:16:52

+0

向我們展示HTML和FF與Chrome中選擇的內容的示例(或更好地創建jsFiddle)。 – glortho 2012-02-22 02:18:33

+0

我很想看到服務器的http://jsfiddle.net/ – mcgrailm 2012-02-22 04:59:17

回答

1

你可以達到類似的效果的時候用一個分數:

document.querySelector(".middle.clear > .post_home").style.paddingLeft = "270px"; 

!important是不必要在這裏,因爲內嵌樣式總是優先,據我所知。

由於jQuery必須在內部運行幾百個命令來創建jQuery對象,然後再設置數百個命令來設置CSS,所以速度更快。

但請注意,IE7及以下版本不支持querySelector,但this article提供了在IE7及更低版本中實現querySelector的極佳方式。

0

嘗試使用eq()選擇器指定要嘗試遍歷的元素集中的索引。您還應該嘗試避免嵌套許多類選擇器,因爲這可能導致性能較差。嘗試使用ID代替。

另外,當您指定!重要的標籤時,請確保在CSS樣式和重要標籤之間不留空格。下面的代碼將添加一個填充左CSS屬性到第一個清除中間一個元素內的類元素。

$('.middle.clear .post_home').eq(0).css('padding-left', '270px!important'); 
0

:first:last,:nth-child(2)這樣的選擇器在所有子元素匹配時都起作用。

在你的情況 $(' .middle.clear > .post_home:first ')將假定你有以下結構

<div class="middle clear"> 
<div class="post_home"> 
<!-- content --> 
</div> 
<!-- no other element of class other than post_home allowed here --> 
<div class="post_home"> 
<!-- content --> 
</div> 
<!-- no other element of class other than post_home allowed here --> 
<div class="post_home"> 
<!-- content --> 
</div> 
<!-- no other element of class other than post_home allowed here --> 
</div> 

這裏所有的子元素都post_home類和所有的人都用你的選擇相匹配。 您還有其他一些與它不匹配的元素,所以您會收到此異常行爲。如果你想使用這種選擇使用ul li sructure: 嘗試使用$(' .middle.clear > .post_home ')[0].style.paddingLeft = "270px";$(' .middle.clear > .post_home ').get(0).style.paddingLeft = "270px";

提示。