2014-10-29 96 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()); 
});