关于如何不使用jQuery获得div的高度有什么想法吗?
我在Stack Overflow中搜索这个问题,似乎每个答案都指向jQuery的.height()。
我尝试了myDiv.style。但是它没有返回任何东西,即使我的div在CSS中设置了它的宽度和高度。
关于如何不使用jQuery获得div的高度有什么想法吗?
我在Stack Overflow中搜索这个问题,似乎每个答案都指向jQuery的.height()。
我尝试了myDiv.style。但是它没有返回任何东西,即使我的div在CSS中设置了它的宽度和高度。
当前回答
js小提琴
var element = document.getElementById('element');
alert(element.offsetHeight);
其他回答
Javascript高度计算
包括填充
使用clientHeight
element.clientHeight
使用offsetHeight
包括填充、边界、border_width
element.offsetHeight
使用el.style.height
它只返回给定的高度(必须有手动高度,例如:<div style="height:12px"></div>,否则返回空结果
element.style.height
使用getBoundingClientRect
包括填充、边境,border_width
elem.getBoundingClientRect();
elem.height
try
myDiv.offsetHeight
console.log(“高度:”,myDiv。offsetHeight); #myDiv{宽度:100px;身高:666 px;背景:红} < div id = " myDiv " > < / div >
var myDiv = document.getElementById('myDiv'); //get #myDiv
alert(myDiv.clientHeight);
clientHeight和clientWidth就是你要找的。
offsetHeight和offsetWidth也返回高度和宽度,但它包括边界和滚动条。根据具体情况,您可以使用其中一种。
希望这能有所帮助。
HTMLElement。返回已定义的元素样式 clientHeight -高度+填充 offsetHeight -高度+填充+边框 scrollHeight -返回高度+填充 getBoundingClientRect() -返回左,上,右,下,x, y, 宽度和高度属性 getComputedStyle() -返回元素的所有CSS属性
// 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); <div id="myDiv" style="margin:10px;padding:20px;height:200px;"> <input type="Text"> <input type="button" value="submit"> </div>
其他答案对我不起作用。下面是我在w3schools找到的,假设div有一个高度和/或宽度设置。
你所需要的是高度和宽度来排除填充。
var height = document.getElementById('myDiv').style.height;
var width = document.getElementById('myDiv').style.width;
不看好你的人:从我收到的好评来看,这个答案至少帮助了5个人。如果你不喜欢,告诉我原因,我好弥补。这是我对反对票最大的不满;你很少告诉我你为什么投反对票。