我已经尝试了一段时间来“获取”我网页上div的高度和宽度。我尝试了很多东西,有些是:
document.getElementById("header").getHeight();
.height();
.height;
.pixelHeight()
以及所有其他'明显'的可能性。有什么帮助吗?它只是一个宽度和高度的简单div:
<style>
#header {
width: 500px;
height:100px;
background-color:black;
border: 2px solid red;
}
</style>
<body>
<div id="header" style="position:absolute" onclick="testjs()" />
<script language="javascript" type="text/javascript">
var hdiv = document.getElementById("header");
function testjs()
{
hdiv.style.height="221px";
}
/////////////////////////////////////
hdiv.getHeight(); ???????
//////////////////////////////////////
</script>
我想'获得'div的高度和宽度,因为最终用户将能够动态地改变高度和宽度。
答案 0 :(得分:7)
获得高度使用
document.getElementById("header").offsetHeight
和宽度用途
document.getElementById("header").offsetWidth;
答案 1 :(得分:3)
你应该考虑获取jQuery,因为那时你可以更容易地使用它:
$("#header").width(); // Gets the width;
$("#header").width(50); // Set width to 50;
$("#header").height(); // Gets the height;
$("#header").height(50); // Set height to 50;
从长远来看,它也会让你的生活变得更轻松。使用原生Javascript编写可能很麻烦,因为它需要更多代码和大量跨浏览器测试。
答案 2 :(得分:0)
示例 -
var divheight = document.getElementById('divId').offsetHeight;
参考这个 -
答案 3 :(得分:0)
如果你不使用jQuery试试这个:
document.getElementById('someDiv').clientHeight;
document.getElementById('someDiv').offsetHeight;
document.getElementById('someDiv').scrollHeight;
取决于你需要的东西。