Javascript 如果另一个第四个元素低于对象内的X像素,则向第一个元素添加边距。页面上有多个对象

Javascript 如果另一个第四个元素低于对象内的X像素,则向第一个元素添加边距。页面上有多个对象,javascript,Javascript,我有一个对象(div),里面有四个元素(带类) 任务:当元素A的高度低于40px时,将其添加到元素B的边距顶部20px 但是,页面上有许多对象 元素A 这里是另一个分区 这里是另一个分区 元素B 元素A 这里是另一个分区 这里是另一个分区 元素B (...) 对不起,我已经试过了。但是,只有当div中只有两个元素时,它才起作用 $(document).ready(function(){ $('.list-name').each(function(index, obj){

我有一个对象(div),里面有四个元素(带类)

任务:当元素A的高度低于40px时,将其添加到元素B的边距顶部20px

但是,页面上有许多对象


元素A
这里是另一个分区
这里是另一个分区
元素B
元素A
这里是另一个分区
这里是另一个分区
元素B
(...)

对不起,我已经试过了。但是,只有当div中只有两个元素时,它才起作用

$(document).ready(function(){
    $('.list-name').each(function(index, obj){
    console.log($(obj).height())
    if($(obj).height() < 40)
    {
       $(obj).next('.product-image-container').css('margin-top', 20)
    }
    });


});
$(文档).ready(函数(){
$('.list name')。每个(函数(索引,obj){
console.log($(obj.height())
如果($(obj).height()<40)
{
$(obj).next('.product image container').css('margin-top',20)
}
});
});
谢谢你的帮助


Rob据我所知,你需要这样的东西:

var heightA = $(".list-name").css("height"); //get height of element. E.g. "20px"
heightA = heightA.substr(0, heightA.length - 2); //remove "px" from string => "20"
if (heightA < 40) { //if the height is less than 40
    $(".product-image-container").css("margin-top", "20px"); //add margin-top 20px
}

. 让我们看看你到目前为止都做了些什么。我们很乐意帮助您。元素A的样式(我指的是高度)是自动生成的。我写的“height:20px”和“height:50px”就是一个例子。不知道这是否是代码不起作用的原因。我还尝试将.css(“height”)更改为.height(),但没有任何帮助。@Rob,或许可以尝试一下:
var heightA = $(".list-name").css("height"); //get height of element. E.g. "20px"
heightA = heightA.substr(0, heightA.length - 2); //remove "px" from string => "20"
if (heightA < 40) { //if the height is less than 40
    $(".product-image-container").css("margin-top", "20px"); //add margin-top 20px
}
var elements = $("body div").length; //get amount of divs. In the HTML you provided 'body' is the parent
for (i = 0; i < elements; i++) { //loop 'em all
    var heightA = $("div:nth-child(" + i + ") .list-name").css("height"); //again get height of corresponding element
    heightA = heightA.substr(0, heightA.length - 2); //remove "px"
    if (heightA < 40) {
        $("div:nth-child(" + i + ") .product-image-container").css("margin-top", "20px"); //set margin-top of corresponding element
    }
}