【问题标题】:Calculate width dynamically (jQuery)动态计算宽度(jQuery)
【发布时间】:2011-01-08 19:46:39
【问题描述】:

HTML:

<div class="parent">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>

jQuery

parentWidth = $(".parent").outerWidth(true);
oneWidth = $(".parent .one").outerWidth(true);
twoWidth = $(".parent .two").outerWidth(true);
$('.parent .three').width( parentWidth - oneWidth - twoWidth);

但问题是,DIV .one 或 .two 有时可能不存在,我该如何修改 jQuery 呢?

谢谢

【问题讨论】:

    标签: jquery dynamic width conditional-statements


    【解决方案1】:

    试试这个代码:

    var third = $('.parent .three');
    var wantedWidth = third.parent().outerWidth(true);
    
    third.siblings().each(function(){
        wantedWidth -= $(this).outerWidth(true);
    });
    
    third.width(wantedWidth);
    

    【讨论】:

      【解决方案2】:

      你为什么不检查 $ 函数的结果是否为空? ;) 这样您就可以轻松找出 div 是否存在,并在这种情况下简单地将宽度设置为 0,例如

      oneDiv = $(".parent .one");
      oneWidth = oneDiv.length == 0 ? 0 : oneDiv.outerWidth(true);
      

      【讨论】:

      • $(selector) 永远不会给你null。如果没有匹配的元素,您只会得到一个空列表包装器。你需要检查例如。 $('.parent .one').length.
      • 感谢您指出这一点,我会修复它。我实际上来自原型世界,其中 $ 为您提供不存在元素的 null。
      【解决方案3】:

      您可以通过检查元素的长度属性来检查元素是否存在:

      parentWidth = $(".parent").outerWidth(true);
      oneWidth = $(".parent .one").length ? $(".parent .one").outerWidth(true):0;
      twoWidth = $(".parent .two").length ? $(".parent .two").outerWidth(true):0;
      $('.parent .three').width( parentWidth - oneWidth - twoWidth);
      

      【讨论】:

      • -1 表示非系统方法和违反 DRY 原则。
      • 感谢您解释您的反对意见,我同意这不是最优雅的解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 2017-11-28
      相关资源
      最近更新 更多