我有一个对象(div),里面有两个元素(带有类)。
任务:当元素A的高度低于40px时,给元素B添加22px的margin-top。
但是页面上有很多对象,以下代码仅查找第一个元素 A(具有类 .list 名称)并向所有元素 B(具有类 .product-image-container)添加边距。
if ($('.list-name').height() < 40) {
$('.product-image-container').css('margin-top','22px');
}
预先感谢您的帮助
抢
最佳答案
这是您所需的解决方案,
- 循环所有
list-name
使用$('.list-name').each()
的类(class)功能。 - 获取下一个
product-image-container
使用(obj).next('.product-image-container')
更接近它 - 更改您需要的 CSS,如
$(obj).next('.product-image-container').css('margin-top', '20px')
$(document).ready(function(){
$('.list-name').each(function(index, obj){
console.log($(obj).height())
if($(obj).height() > 20)
{
$(obj).next('.product-image-container').css('background', 'green')
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<div class="list-name" style="height: 20px">list-name 1</div>
<div class="product-image-container">product-image-container 1</div>
</div>
<div>
<div class="list-name" style="height: 40px">list-name 2</div>
<div class="product-image-container">product-image-container 2</div>
</div>
</body>
</html>
请运行上面的代码片段
关于Javascript:如果对象内另一个元素高于 X 像素,则为该元素添加边距。页面上有多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49774621/