Get DIV width and height in javascript

江枫思渺然 提交于 2019-12-03 02:51:42

Since you're already using jQuery, you can just do:

var width;

if (need == 1) {
   width = $("#web").width();
} else {
   width = $("#set").width();
}
Daidai

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"), // Do not use #
    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"), // Do not use #
    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 just get the width of ele.style, not the real width of ele.

If you have done something like:

ele.style.width = "55px"

You get "55px" when using ele.style.width. 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.

In plain vanilla JavaScript use

var width = mydiv.offsetWidth;
var height = mydiv.offsetHeight;

This will give you numeric values, or

var width = mydiv.offsetWidth + 'px';
var height = mydiv.offsetHeight + 'px';

If you want them in "CSS" format.

Since you're using jQuery, you'll probably want to know about the following:

$('#id').outerWidth() $('#id').outerWidth(true)

These will come in very handy. This allows you to find the total width of the div (padding, border, width and (optional argument) margin).

http://api.jquery.com/outerWidth/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!