How to get ele开发者_开发问答ment 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
).
.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/
Maybe
elt.getBoundingClientRect().width
This worked for me:
document.getElementById().offsetWidth;
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.
精彩评论