欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js之can't Get DIV width and height

程序员文章站 2022-05-17 22:15:48
...
Get DIV width and height in javascript

=========================================
http://www.iteye.com/problems/50940
首先,你的代码中没有申明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.





http://*.com/a/16474226/2893073








-