2012-03-19 11 views
1

私は1つの親divを持ち、3つの子divを持ちます。すべての子は同じheadinigタグ "h3"を含んでいます。最初のタグを除いてh3タグに10pxのパディングを追加したいhtmlと対話することなく例えば、最初にh3 =パディングトップ= 0; 2番目のh3 =パディングトップ= 10px。 3番目のh3 =パディングトップ= 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セレクタを使用しますが、他の<h3> sが.mainであり、あなたが.boxの中にあるもので唯一興味があれば、セレクタを調整し、http://jsfiddle.net/ambiguous/f3fmC/

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

デモを

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

デモ:http://jsfiddle.net/ambiguous/DYTmL/

そして、あなたはeach<h3> Sを反復処理、増加padding-topを使用する場合:

$('.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でパディングを追加しないでください。jqueryの.notメソッドを使用していますが、次のh3 10px 2番目のh3は20pxです。もし30px以上のものがあれば – Carlos

+0

@amit:ああ、私は増加するパディングに気づいていません。私の更新を確認してください。 –

+0

ありがとうございました – Carlos

0

css :nth-child pseudo classを使用してください。

+0

http://www.w3.org/wiki/CSS/Selectors/pseudo-classes/:nth-child –

+0

それ文句を言わない仕事つまり、 – Carlos

+0

jqueryにもnth-childセレクタがあります。http://api.jquery.com/nth-child-selector/それは動作しますか?私は知らない、申し訳ありませんが、私は持っていません –

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ではパディングを追加しません。jqueryの.notメソッドを使用しますが、次のh3 10px h3は20pxです。もしそれに30px以上のものがある場合は、 – Carlos

+0

の追加の回答を見てください。そういう意味ですか? –

関連する問題