开发者

Calculate width dynamically (jQuery)

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( parentWid开发者_JS百科th - oneWidth - twoWidth);

But the thing is, either DIV .one or .two may not exist some times, how do I modify the jQuery for it?

Thanks


You can check if an element exists by checking its length property:

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);


Why don't you just check whether the result of $ function is empty ? ;) That way you can easily find out whether the div exists and simply set the width to 0 in that case, e.g.

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


Try this code:

var third = $('.parent .three');
var wantedWidth = third.parent().outerWidth(true);

third.siblings().each(function(){
    wantedWidth -= $(this).outerWidth(true);
});

third.width(wantedWidth);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜