开发者

How to get width and height of an element on the page?

With the help of the lovely jQuery开发者_StackOverflow社区?


jQuery has two methods, width and height, to do this very thing:

$(".myElement").width();
$(".myElement").height();

You can also use them to SET values:

$(".myElement").width(200); // set element to 200px

Further information can be found in the documentation: http://api.jquery.com/width/ and http://api.jquery.com/height/

Note the other dimension methods available too:

  • $.innerHeight() - Get the current computed height for the first element in the set of matched elements, including padding but not border.
  • $.innerWidth() - Get the current computed width for the first element in the set of matched elements, including padding but not border.
  • $.outerHeight() - Get the current computed height for the first element in the set of matched elements, including padding and border.
  • $.outerWidth() - Get the current computed width for the first element in the set of matched elements, including padding and border.


Using the height(...) and width(...) methods:

alert($(body).height());
alert($(body).width());


You'll never guess...

var width = $(selector).width();
var height = $(selector).height();


In various useful cases, the width value is often wrong on Mac Firefox/Mozilla.

-- where wrong means that if you set an enclosing div to the reported "width" of the text-child, you'll get wrapping.

The problem is that on Mac Firefox/Mozilla, Firefox uses sub-pixel font rendering. And the width that is returned is the floor, not the ceiling of the true width, which is a float.

My bug report gives a work-around for Firefox, or just always add 1px to the width and you'll be ok.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜