使用jQuery根据其他元素的高度添加上边距

时间:2011-12-15 08:28:44

标签: jquery css height

我有高度错误的元素。我需要根据第一个块添加一些margin-top到其他元素。我被用于这个动作jQuery高度属性,但它不起作用。你能帮助我吗?

这是我的代码:

$(document).ready(function(){
    if ($('.post_discussion_header').height(79) + 'px'){
        $('.no_0').css('margin-top','110px');
        }
    });
});

TIA。

4 个答案:

答案 0 :(得分:2)


$(document).ready(function(){
    if ($('.post_discussion_header').height() == 79) {
        $('.no_0').css('margin-top','110px');
    }
});

答案 1 :(得分:2)

您的if语句错误,应该是

   if ($('.post_discussion_header').height() == 79){

但是你可以考虑使用偏移高度来返回元素的高度,包括边框和填充(如果有的话),但不是边距https://developer.mozilla.org/en/DOM/element.offsetHeight

   if (parseInt($('.post_discussion_header')[0].offsetHeight,10) == 79){ 

编辑:添加了parseInt,将“79px”转换为79进行比较http://www.w3schools.com/jsref/jsref_parseInt.asp

你也有太多});在你的代码中。第5行应该是}

答案 2 :(得分:0)

$('.post_discussion_header').height(79).post_discussion_header的高度设置为79,并返回.post_discussion_header。然后,您将该标头与'px'连接起来。您的代码将评估为

if('[object Object]px') {
    ...
}

显然,这不是你的意图。问题是, 你的意图是什么?你想检查什么条件?

您的代码中还有一组});太多。

答案 3 :(得分:0)

尝试使用.css("height")这应该为你做!
但是不要忘记如果你试图将高度添加到div元素的实际高度,jQuery.css(“height”)返回“23px”,所以你必须删除“px”才能添加一些整数值。

相关问题