简体   繁体   中英

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

借助可爱的jQuery?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM