我正在使用 jQuery 从一个 div 获取高度并通过 css 将其添加到另一个
所以我有以下布局作为示例:
<div class="row">
<div class="column image">
<img src="image.jpg" />
</div>
<div class="column content">
<p>Content</p>
</div>
</div>
<div class="row">
<div class="column content">
<p>Content</p>
</div>
<div class="column image">
<img src="image.jpg" />
</div>
</div>
使用以下 jQuery
function showHeight( element, height ) {
$( "div.image" ).css("height", height);
}
showHeight( "div", $( ".content" ).height() );
我将从“.content”获取高度并将该高度重新放入“.image”
现在显然这适用于一个实例,但我希望在多个实例上使用它,而不是为每个实例编写一个函数。
最佳答案
您可以遍历 .image
元素并根据 prev('.content')
元素更改其 height
。
function updateHeight() {
// loop through all image elements
$( "div.image" ).each(function(){
// get `height` of the previous `.content` element
var contentHeight = $(this).prev('.content').height();
// set height
$(this).css("height", contentHeight);
});
}
//call one method to update
updateHeight();
这仅在 .image
位于 .content
之后时才有效。我像这样重新排序了 HTML:
<div class="row">
<div class="column content">
<p>Content</p>
</div>
<div class="column image">
<img src="image.jpg" />
</div>
</div>
<div class="row">
<div class="column content">
<p>Content</p>
</div>
<div class="column image">
<img src="image.jpg" />
</div>
</div>
更新:
要以任何顺序查找最接近的 .content,请更改此
var contentHeight = $(this).prev('.content').height();
到
var contentHeight = $(this).prev('.content').height() || $(this).next('.content').height();
关于javascript - 根据 jQuery 中多个实例的另一个元素高度设置高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34866544/