js之can't Get DIV width and height

Get DIV width and height in javascript

=========================================
[url]http://www.iteye.com/problems/50940[/url]
首先,你的代码中没有申明DTD,所以,在IE下,id=div1的div表现为height就是最小高,类似于min-height(IE6不识别该属性),所以,它的高将随内容而走。默认的,浏览器里的字大小为16px,所以,你的div在IE下的高度就是16px,即使你设置了height,这个div的高度,仍然会随你的内容而变化。但是,如果你去FireFox下打开的话,那么,你设置的这个div的高度将是起作用的。因为,FireFox是遵守W3C标准的。具体的内容可以通过给div给border来查看。
举例:
<div style="height:6px;border:1px solid #000;">ABC</div>
将这个内容放置在一个单独的html中,分别用IE和FireFox打开看一下就可以知道差别了。
想让他们保持一致的话,请给页面的第一行加上一下内容:
<!DOCTYPE html>
然后在对比IE和FF

其次,div是一个无样式属性的标签,你对div设置的width,height都是错误的,这些属性只有写在style里或者css中才有效。

============================================
It's quite wrong to use ele.style.width to get the element's width!!!!!!

In native JavaScript,you can get a element's CSS through two ways:

Standard Method

window.getComputedStyle(ele)
For example,

var ele = document.getElementById("#content"),
eleStyle = window.getComputedStyle(ele);
/* Below is the width of ele */
var eleWidth = eleStyle.width;
IE(IE 8 And Before)

element.currentStyle
For example,

var ele = document.getElementById("#content"),
eleStyle = ele.currentStyle;
/* Below is the width of ele */
var eleWidth = eleStyle.width;
Why Not Use ele.style?

ele.style is just get the attribule style of ele.If you use ele.style.width,you can just get the width of ele.style,not the real width of ele.

If you have done something like

ele.style.width = "55px"
,you can get "55px" when using ele.style.widht.If you haven't,you will get undefined.

How To Do In jQuery?

Use $ele.width() (if you want the "exact" width,use $ele.outWidth()),jQuery has done everything for you.


[url]http://stackoverflow.com/a/16474226/2893073[/url]


-
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值