Javascript 获取div高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10747209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:46:13  来源:igfitidea点击:

Getting div height

javascripthtml

提问by Rose Perrone

Firebug tells me the computed style of my_div:

Firebug 告诉我的计算样式my_div

width 300px

宽度 300px

height 453.167px

高度 453.167px

Yet when I execute console.log(mydiv.style.height), it gives me an empty string, even though console.log(mydiv)logs the correct element. I am sure the page has loaded by the time this logging code is called. I'd appreciate a solution that does not use jQuery.

然而,当我执行时console.log(mydiv.style.height),它给了我一个空字符串,即使console.log(mydiv)记录了正确的元素。我确定在调用此日志记录代码时页面已加载。我很感激不使用 jQuery 的解决方案。

回答by josh.trow

Depending on the browser of choice, one of these will do:

根据选择的浏览器,其中之一将执行以下操作:

mydiv.offsetHeight
mydiv.clientHeight

Get full height of a clipped DIV

获取剪切的 DIV 的全高

Getting the height of a div

获取div的高度

回答by Alex K

UPDATE:

更新:

Many browser inconsistencies have been fixed since my original answer. Now the clientHeightproperty of a DOM element is reliable.

自从我的原始答案以来,许多浏览器不一致问题已得到解决。现在clientHeightDOM 元素的属性是可靠的。

var height = element.clientHeight;

var height = element.clientHeight;

The Element.clientHeight read-only property is zero for elements with no CSS or inline layout boxes, otherwise it's the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin.

clientHeight can be calculated as CSS height + CSS padding - height of horizontal scrollbar (if present).

Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect().

对于没有 CSS 或内联布局框的元素,Element.clientHeight 只读属性为零,否则它是元素的内部高度(以像素为单位),包括填充但不包括水平滚动条高度、边框或边距。

clientHeight 可以计算为 CSS 高度 + CSS 填充 - 水平滚动条的高度(如果存在)。

注意:此属性会将值四舍五入为整数。如果需要小数值,请使用 element.getBoundingClientRect()。

Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight

来源:https: //developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight

Original answer:

原答案:

If you use the jQuery JS library, you can just do this:

如果你使用 jQuery JS 库,你可以这样做:

var computed_height = $('#my_div').height();

If you use the Prototype JS library, it's similar:

如果使用 Prototype JS 库,则类似:

var computed_height = $('my_div').getHeight();

Using a library is often the easiest & most cross-browser way to do something. Getting computed styles with vanilla js is unreliable because the properties are different across browsers.

使用库通常是做某事最简单和最跨浏览器的方式。使用 vanilla js 获取计算样式是不可靠的,因为不同浏览器的属性不同。