简体   繁体   中英

jQuery.width() and height() returns different value on IE and Chrome

I am showing a nvd3 chart on bootstrap modal. I specified width and height of modal-body with css:

#trendModal .modal-dialog {
    width: 800px;
}

#trendModal .modal-body {
    height: 400px;
}

<div class="modal fade" id="trendModal" tabindex="-1" role="dialog" aria-labelledby="trendModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="trendModalLabel"></h4>
            </div>
            <div class="modal-body" id="trend-container">
                <svg></svg>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

However, when I try to get width and height of modal, I get different answer on IE and Chrome:

width = $("#trendModal .modal-dialog").width(), //IE: 800, Chrome:780
height = $("#trendModal .modal-body").height(), //IE: 400, Chrome:360

It looks like Chrome deduct some padding/margin automatically while IE doesn't. Does anyone know how this comes? If I want to unify behavior, what should I do? Thanks.

This should work:

var width = $("#trendModal .modal-dialog").outerWidth()
    height = $("#trendModal .modal-body").outerHeight();

These give you the total height and width of the element including any margin and padding they might contain.

There can be an issue in Chrome where the height/width is calculated with the document ready trigger, which won't take into account how the content could alter the width/height. Have you tried $(document).load(...)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM