简体   繁体   中英

What is the equivalent of .height() and .width() of jQuery in pure JavaScript?

Is there any equivalent cross browser API for getting the content height and width which don't include border size, padding and margin? I don't have the option of using jQuery.

Edit: Forgot to mention, I have to support IE 8 too.

Well, I have managed to come to a solution. For browsers except IE<9, Window.getComputedStyle() is to the rescue. The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain. See https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle for more details on that.

Problem is with IE 8 and earlier. getComputedStyle is undefined in them. Fortunately IE has proprietary currentStyle property from which we could retrieve content width and height . Sad but true that, if we declared width in % in stylesheets, it would return in % also.

So the problem remains is, we need a way to convert from percentage to pixel values. There is a hack from Dean Edwards for solving this problem. Thanks to him !

    var PIXEL = /^\d+(px)?$/i;
    function getPixelValue(element, value) {
        if (PIXEL.test(value)) return parseInt(value);
        var style = element.style.left;
        var runtimeStyle = element.runtimeStyle.left;
        element.runtimeStyle.left = element.currentStyle.left;
        element.style.left = value || 0;
        value = element.style.pixelLeft;
        element.style.left = style;
        element.runtimeStyle.left = runtimeStyle;
        return value;
    };

So, finally the cross-browser solution of finding content width( logic for calculating height is same except query for height instead of width ) using the hack is as follows:

Suppose we have a div with id 'container' . Its width is set as 50% in the style sheet.

 <style type="text/css">

    #container {
        width: 50%;
        padding: 5px;
    }

  </style>

Test JavaScript Code:

var container = document.getElementById('container');
if (window.getComputedStyle) {
      var computedStyle = getComputedStyle(container, null)
      alert("width : "+computedStyle.width);
} else {
      alert("width : "+getPixelValue(container,container.currentStyle.width)+'px');
}

According to the http://youmightnotneedjquery.com/ it's

parseFloat(getComputedStyle(el, null).height.replace("px", ""))

and

parseFloat(getComputedStyle(el, null).width.replace("px", ""))

for IE9+.

通常是offsetWidth和offsetHeight。

   document.getElementById("elemID").clientWidth;
   document.getElementById("elemID").clientHeight;

Here elemID is the element ID

Yes, there is innerWidth and innerHeight.

So something like

var obj = document.getElementById('idhere');
var width = obj.innerWidth...

使用此document.getElementById(“elementID”)。style.height;

TL;DR: jQuery(window) equivalent:

WIDTH: jQuery(window).width() => document.querySelector('html').clientWidth
or document.body.clientWidth with no horizontal scrollbar

HEIGHT: jQuery(window).height() => document.querySelector('html').clientHeight


I did some tests around this while rewriting old jQuery code and I want to mention
the equivalent of $(window) which does not (always) equal towindow.clientWidth/Height !

Example of a window dimensions (opened developer tools)

(example for a page opened in Chrome (v104))

A. WITH scrollbars (both vertical and horizontal)

#HTMLElement == document.querySelector('html')

          width                   |              height
jQuery(window).width():    1905   |   jQuery(window).height():      509
document.body.clientWidth: 1905   |   document.body.clientHeight: 14000
#HTMLElement.clientWidth:  1905   |   #HTMLElement.clientHeight:    509 // EQUAL to jQuery
window.innerWidth:         1920   |   window.innerHeight:           524
window.outerWidth:         1920   |   window.outerHeight:          1055

B. NO scrollbar (overflow hidden on body)

#HTMLElement == document.querySelector('html')

          width                   |              height
jQuery(window).width():    1920   |   jQuery(window).height():      524
document.body.clientWidth: 1920   |   document.body.clientHeight: 14000
#HTMLElement.clientWidth:  1920   |   #HTMLElement.clientHeight:    524 // still $ equal
window.innerWidth:         1920   |   window.innerHeight:           524 // only without SB
window.outerWidth:         1920   |   window.outerHeight:          1055

Now why did I include the <html> element there? That's because other width/height sources do not reflect the values from jQuery because they don't account for scrollbars.

The core difference

jQuery accounts for scrollbars ,
native window properties do not ,
however html Element does.

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