2012-03-19 61 views
1

我在裏面有簡單的html我有一個父div,它有3個子div,每個子包含相同的headinig標籤「h3」我想添加10px填充h3標籤,不包括第一個標籤不與html進行交互。例如第一個h3 = padding top = 0;第二個h3 = padding top = 10px;第三個h3 = padding top = 20px;通過jquery在標題標記中添加填充

<style> 

.main { width:980px; margin:0 auto; border:solid 1px #F00; overflow:hidden} 

.box { width:300px; float:left; margin-right:20px; background:#00F; height:200px;} 


</style> 

<script type="text/javascript" src="jquery/jquery-1.7.min.js"></script> 
<script type="text/javascript"> 
$(function(){ 
    //code 

    }) 

</script> 

</head> 

<body> 
<div class="main"> 
<div class="box"><h3>first</h3></div> 
<div class="box"><h3 style="padding-top:10px;">second</h3></div> 
<div class="box"><h3 style="padding-top:20px;">third</h3></div> 

</div> 

</body> 

回答

5

使用:not:first選擇:

$('.main h3:not(:first)').css('paddingTop', '10px');​ 

演示:http://jsfiddle.net/ambiguous/f3fmC/

如果有其他<h3> S IN .main而你只有在那些裏面.box興趣,然後調整選擇:

$('.main .box:not(:first) h3').css('paddingTop', '10px');​ 

演示:http://jsfiddle.net/ambiguous/DYTmL/

如果你想使用越來越padding-top,通過<h3> s的each迭代:

$('.main h3:not(:first)').each(function(i) { 
    $(this).css('paddingTop', (i + 1) * 10); 
});​ 

演示:http://jsfiddle.net/ambiguous/QuyWj/

或者簡單:

$('.main h3').each(function(i) { 
    $(this).css('paddingTop', i * 10); 
});​ 

演示:http://jsfiddle.net/ambiguous/YAYJw/

+0

你的ans是非常接近解決我的問題,它不是在第一個h3添加填充,因爲我們使用.not方法的jquery,但我想添加pading在接下來的h3 10px和旁邊第二個h3是20像素,如果我有一個超過30像素到 – Carlos 2012-03-19 04:48:19

+0

@amit:啊,我沒有注意到增加的填充。請檢查我的更新。 – 2012-03-19 04:52:38

+0

謝謝很多先生,它正在工作 – Carlos 2012-03-19 04:52:49

0
+0

http://www.w3.org/wiki/CSS/Selectors/pseudo-classes/:nth-child – 2012-03-19 04:32:54

+0

,但它不會工作在即 – Carlos 2012-03-19 04:33:17

+0

jquery也有nth-child選擇器太http://api.jquery.com/nth-child-selector/可能是有效的?我不知道,對不起,我沒有ie – 2012-03-19 04:35:16

1

嘗試:


$(document).ready(function() { 
    $(".box h3").not(":first").css("paddingTop","10px"); 
}); 

你的意思是:


$(document).ready(function() { 
    var paddingTop = 10; 
    $(".box h3").not(":first").each(function() { 
     $(this).css("paddingTop",paddingTop+"px"); 
     paddingTop +=10; 
    }); 
}); 
+0

你的ans是非常接近解決我的問題,它不是在第一個h3中添加填充,因爲我們使用.not方法的jquery,但我想在下一個hpx 10px中添加pading,然後在第二個h3是20像素,如果我有一個超過30像素到 – Carlos 2012-03-19 04:50:58

+0

看到額外的答案,你的意思是這樣的..? – 2012-03-19 04:54:21