关于如何不使用jQuery获得div的高度有什么想法吗?
我在Stack Overflow中搜索这个问题,似乎每个答案都指向jQuery的.height()。
我尝试了myDiv.style。但是它没有返回任何东西,即使我的div在CSS中设置了它的宽度和高度。
关于如何不使用jQuery获得div的高度有什么想法吗?
我在Stack Overflow中搜索这个问题,似乎每个答案都指向jQuery的.height()。
我尝试了myDiv.style。但是它没有返回任何东西,即使我的div在CSS中设置了它的宽度和高度。
当前回答
<div id="item">show taille height</div>
<script>
alert(document.getElementById('item').offsetHeight);
</script>
杰斯菲德尔
其他回答
try
myDiv.offsetHeight
console.log(“高度:”,myDiv。offsetHeight); #myDiv{宽度:100px;身高:666 px;背景:红} < div id = " myDiv " > < / div >
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
js小提琴
var element = document.getElementById('element');
alert(element.offsetHeight);
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>
var myDiv = document.getElementById('myDiv'); //get #myDiv
alert(myDiv.clientHeight);
clientHeight和clientWidth就是你要找的。
offsetHeight和offsetWidth也返回高度和宽度,但它包括边界和滚动条。根据具体情况,您可以使用其中一种。
希望这能有所帮助。