Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
324 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...