简体   繁体   English

纯 JavaScript 中 jQuery 的 .height() 和 .width() 的等价物是多少?

[英]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?是否有任何等效的跨浏览器 API 用于获取不包括边框大小、填充和边距的内容高度和宽度? I don't have the option of using jQuery.我没有使用 jQuery 的选项。

Edit: Forgot to mention, I have to support IE 8 too.编辑:忘了提,我也必须支持 IE 8。

Well, I have managed to come to a solution. 好吧,我设法找到了解决方案。 For browsers except IE<9, Window.getComputedStyle() is to the rescue. 对于除IE <9之外的浏览器, Window.getComputedStyle()是为了解决问题。 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. Window.getComputedStyle()方法在应用活动样式表并解析这些值可能包含的任何基本计算后,给出元素的所有CSS属性的值。 See https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle for more details on that. 有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle

Problem is with IE 8 and earlier. IE 8及更早版本存在问题。 getComputedStyle is undefined in them. getComputedStyle在其中undefined Fortunately IE has proprietary currentStyle property from which we could retrieve content width and height . 幸运的是,IE具有专有的currentStyle属性,我们可以从中检索内容的widthheight Sad but true that, if we declared width in % in stylesheets, it would return in % also. 很遗憾但是,如果我们在样式表中以%表示width ,它也将以%返回。

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: 因此,最后使用hack查找内容宽度(计算高度的逻辑除了查询高度而不是宽度)的跨浏览器解决方案如下:

Suppose we have a div with id 'container' . 假设我们有一个id为'container'div Its width is set as 50% in the style sheet. 样式表中的宽度设置为50%。

 <style type="text/css">

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

  </style>

Test JavaScript Code: 测试JavaScript代码:

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根据http://youmightnotneedjquery.com/它是

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

and

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

for IE9+.适用于 IE9+。

通常是offsetWidth和offsetHeight。

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

Here elemID is the element ID 这里elemID是元素ID

Yes, there is innerWidth and innerHeight. 是的,有innerWidth和innerHeight。

So something like 所以像

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

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

TL;DR: jQuery(window) equivalent: TL;DR: jQuery(window)等价物:

WIDTH: jQuery(window).width() => document.querySelector('html').clientWidth宽度: jQuery(window).width() => document.querySelector('html').clientWidth
or document.body.clientWidth with no horizontal scrollbar或没有水平滚动条的document.body.clientWidth

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


I did some tests around this while rewriting old jQuery code and I want to mention我在重写旧的 jQuery 代码时对此做了一些测试,我想提一下
the equivalent of $(window) which does not (always) equal to相当于$(window)不(总是)等于window.clientWidth/Height !

Example of a window dimensions (opened developer tools) window尺寸示例(打开的开发人员工具)

(example for a page opened in Chrome (v104)) (在 Chrome (v104) 中打开的页面示例)

A. WITH scrollbars (both vertical and horizontal) A. WITH滚动条(垂直和水平)

#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) B.没有滚动条(溢出隐藏在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?现在我为什么要在其中包含<html>元素? That's because other width/height sources do not reflect the values from jQuery because they don't account for scrollbars.这是因为其他宽度/高度源不反映 jQuery 的值,因为它们不考虑滚动条。

The core difference核心区别

jQuery accounts for scrollbars , jQuery 占滚动条
native window properties do not ,本机window属性不
however html Element does.但是html Element可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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