How do I retrieve an HTML element's actual width and height?

前端 未结 14 1685
后悔当初
后悔当初 2020-11-22 02:29

Suppose that I have a

that I wish to center in the browser\'s display (viewport). To do so, I need to calculate the width and height of the &l
14条回答
  •  灰色年华
    2020-11-22 02:58

    NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.

    As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

    var height = $("#myDiv").height();
    var width = $("#myDiv").width();
    
    var docHeight = $(document).height();
    var docWidth = $(document).width();
    

提交回复
热议问题