当前位置: 代码迷 >> JavaScript >> 如果获得一个div的宽高,该怎么处理
  详细解决方案

如果获得一个div的宽高,该怎么处理

热度:37   发布时间:2012-04-07 17:31:50.0
如果获得一个div的宽高
<div   id= "test "> 你知道我的长宽么 </div>

<script>
var   test=document.getElementById( "test ");
document.write( "长: "+test.style.pixelWidth);
document.write( "长: "+test.width);
</script>


这个div没有进行任何width,height的定义,里面写了些文字
想知道这个div的宽高,如何实现?

------解决方案--------------------
<div id= "test " style= "background-color: yellow "> 你知道我的长宽么 </div>

<script>
var test=document.getElementById( "test ");
document.write( "宽: "+test.offsetWidth);
document.write( "高: "+test.offsetHeight);
</script>

妥了,哈
------解决方案--------------------
如果设置高度和宽度
可以用currentStyle.height和currentStyle.width
如果没有设置,使用offsetHeight
<div id= "div1 ">
asdasd
</div>
<script language=javascript>
alert(document.getElementById( "div1 ").offsetHeight)
alert(document.getElementById( "div1 ").offsetWidth)
</script>
  相关解决方案