【问题标题】:Add top-margin based on height of other element with jQuery使用jQuery根据其他元素的高度添加上边距
【发布时间】:2012-01-20 23:22:30
【问题描述】:

我有具有杂项高度的元素。我需要根据第一个块向其他元素添加一些边距顶部。我曾用于此操作 jQuery 高度属性,但它不起作用。你能帮助我吗?

这是我的代码:

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

TIA。

【问题讨论】:

  • 您的 if 语句错误,您要验证什么?

标签: jquery css height


【解决方案1】:

你的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 行应该只是 }

【讨论】:

  • @ukasz-borawski 记得点击接受回答按钮 ;-)
  • 完成了,再一次,谢谢!我也加了> 70,现在我有一些灵活的动作......所以它的工作更好
【解决方案2】:
$(document).ready(function(){ if ($('.post_discussion_header').height() == 79) { $('.no_0').css('margin-top','110px'); } });

【讨论】:

    【解决方案3】:

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

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

    显然,这不是你的本意。问题是,你的意图是什么?您要检查什么情况?

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

    【讨论】:

    • 我有 .post_discussion_header 女巫没有选择高度。当我的标题有一两行时设置此属性。如果它有一行少于 79px 并且它溢出到 .no_0 bcs .post_discussion_header set display on fixed... :(
    【解决方案4】:

    尝试与.css("height") 合作,这应该会为您服务!
    但不要忘记,如果您尝试将高度添加到 div 元素的实际高度,jQuery.css("height") 返回“23px”,因此您必须先删除“px”,然后才能添加一些整数价值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      相关资源
      最近更新 更多