动态计算宽度(jQuery)

3zz*_*zzy 2 jquery dynamic width conditional-statements

HTML:

<div class="parent">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

jQuery的

parentWidth = $(".parent").outerWidth(true);
oneWidth = $(".parent .one").outerWidth(true);
twoWidth = $(".parent .two").outerWidth(true);
$('.parent .three').width( parentWidth - oneWidth - twoWidth);
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Joh*_*lum 6

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

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);
Run Code Online (Sandbox Code Playgroud)