lwi*_*iii 287 html javascript css
关于如何在不使用jQuery的情况下获得div高度的任何想法?
我正在搜索Stack Overflow这个问题,似乎每个答案都指向jQuery .height().
我尝试了类似的东西myDiv.style.height,但它什么也没有返回,即使我的div有它width并且height设置在CSS中.
Dan*_*Dan 538
var clientHeight = document.getElementById('myDiv').clientHeight;
Run Code Online (Sandbox Code Playgroud)
要么
var offsetHeight = document.getElementById('myDiv').offsetHeight;
Run Code Online (Sandbox Code Playgroud)
clientHeight 包括填充.
offsetHeight 包括填充,滚动条和边框.
Dan*_*mms 21
var element = document.getElementById('element');
alert(element.offsetHeight);
Run Code Online (Sandbox Code Playgroud)
use*_*883 19
另一种选择是使用getBoundingClientRect函数.请注意,如果元素的显示为"none",则getBoundingClientRect将返回一个空矩形.
例:
var elem = document.getElementById("myDiv");
if(elem) {
var rect = elem.getBoundingClientRect();
console.log(rect.height);
}
Run Code Online (Sandbox Code Playgroud)
Sah*_*mar 18
// returns defined Style of element
const styleHeight = document.getElementById('myDiv').style.height;
console.log('style Height : ', styleHeight);
// height + padding
const clientHeight = document.getElementById('myDiv').clientHeight;
console.log('client Height : ', clientHeight);
// height + padding + borders
const offsetHeight = document.getElementById('myDiv').offsetHeight;
console.log('offset Height : ', offsetHeight);
// height + padding
const scrollHeight = document.getElementById('myDiv').scrollHeight;
console.log('scroll Height : ', scrollHeight);
// return left, top, right, bottom, x, y, width, and height properties
const getBoundingClientRectHeight = document.getElementById('myDiv').getBoundingClientRect().height;
console.log('get Bounding Client Rect Height : ', getBoundingClientRectHeight);
// returns all CSS properties of an element
const styleElementHeight = getComputedStyle(document.getElementById("myDiv")).height;
console.log('style Element Height : ', styleElementHeight);Run Code Online (Sandbox Code Playgroud)
<div id="myDiv" style="margin:10px;padding:20px;height:200px;">
<input type="Text">
<input type="button" value="submit">
</div>Run Code Online (Sandbox Code Playgroud)
Keo*_*ife 10
var myDiv = document.getElementById('myDiv'); //get #myDiv
alert(myDiv.clientHeight);
Run Code Online (Sandbox Code Playgroud)
clientHeight和clientWidth是您正在寻找的.
offsetHeight和offsetWidth也返回高度和宽度,但它包括边框和滚动条.根据具体情况,您可以使用其中一种.
希望这可以帮助.
其他答案对我不起作用。这是我在w3schools找到的内容,假设div有一个height和/或width集合。
您所需要的height只是width排除填充。
var height = document.getElementById('myDiv').style.height;
var width = document.getElementById('myDiv').style.width;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
462557 次 |
| 最近记录: |