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

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

javascript - 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!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...