2014-10-29 79 views
0

我有一個具有結構相同的多個元素的網頁:設置多個HTML標籤

<img class="rollover" src="http://www.example.com/images/rollover.png"/> 
<div class="text"> 
    <h3>Example 1</h3> 
</div> 

<img class="rollover" src="http://www.example.com/images/rollover.png"/> 
<div class="text"> 
    <h1>Example 2</h1> 
</div> 

我想設置與類的img標籤的高度=」翻轉「到與class =」text「的下一個div相同的高度。這些頁面上可能會出現一個或多個。我有一些基本的jQuery可以設置高度相等,但它將所有圖像設置爲相同的高度。我怎樣才能調整它,使它只需要下一個div的高度?

$('.rollover').height($('.text').height()); 
+0

你絕對必須使用'class'爲'text'或者你可以使用'id'代替? – starvator 2014-10-29 18:25:33

回答

2

如果您的代碼中總是顯示相應的imgs和text-div,則此方法有效。

var txt = $('.text'); 
$('.rollover').each(function(i) {$(this).height(txt.eq(i).height());}); 
0

試試這個:

var x = $(".rollover").length; 
for(var i=1; i<=x; i++) 
{ 
    var h = $(".rollover:nth-child('+i+'").next(".text").height(); 
    $(".rollover:nth-child('+i+').height(h); 
} 
+2

您的答案出現在低質量答案堆中以供審閱,也許您可​​以在一小段文字中添加有關此答案爲何以及如何起作用的文字? – t0mppa 2014-10-29 20:22:51

0

你可以把每對IMG和DIV的一個新的div元素裏面。這將提高代碼的可讀性...

<div class="eaqualHeight"> 
    <img class="rollover" src="http://www.example.com/images/rollover.png"/> 
    <div class="text"> 
    <h3>Example 1</h3> 
    </div> 
</div> 

<div class="eaqualHeight"> 
    <img class="rollover" src="http://www.example.com/images/rollover.png"/> 
    <div class="text"> 
    <h1>Example 2</h1> 
    </div> 
</div> 

然後用下面的jQuery代碼...

$('.eaqualHeight').each(function(){ 
    $(this).children('.rollover').height($(this).children('.text').height()); 
});