简体   繁体   中英

Get element width in px

How to get element width in pixels (px)? jQuery always returns value in percent (pct).

HTML

<span class="myElement"></span>

CSS

.myElement {
  float: left;
  width: 100%;
  height: 100%;
}

JavaScript

$('span.myElement').css('width') // returns '100%'
$('span.myElement').width() // returns '100'

Thanks!

How many items have the class myElement ? Consider using an id , not a class , as getting the width of two elements is not really possible (or logically understandable IMO).

I made a little demo, and for me, it outputs the width in pixels for a single span element with a width of 100% (for me, it alerts something around 400 ): http://jsfiddle.net/LqpNK/3/ .

By the way, <span> element's can't have a set width or height, so setting their width and height does you no good. Instead, display them as a block element (so just replace <span> with <div> , or add display: block; to the CSS of .myElement ).

也许

elt.getBoundingClientRect().width

.css('width') should return 100%, however .width() should (as described here http://api.jquery.com/width/ ) return a unit-less pixel amount. I created a jsfiddle to demonstrate: http://jsfiddle.net/yxCav/

From the jQuery documentation on width()

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

So it returns pixels if the pixel width is defined, but you are defining the width in %

I have experienced like in this post: jQuery width() not returning correct value on a div with generated content . If the div is not displayed earlier or are loading content dynamically, the .width() function returns the percentage value, but till the element is fully loaded the same .width() function will return width in pixels.

这对我有用:

document.getElementById().offsetWidth;

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