Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - Getting the actual, floating-point width of an element

I'm using jQuery (v1.7.1) and I need to get the absolute, floating-point width of an element, but all of jQuery's width methods seem to be rounding-off the value of the width.

For example if the actual width of an element was 20.333333px, jQuery's width method returns 20, i.e ignoring the decimal value.

You can see what I mean on this jsFiddle

So, my question is: How do I get the floating-point value of the width of an element?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you already have a reference to the DOM element, element.getBoundingClientRect will get you the values you want.

The method has existed since Internet Explorer 4, and so it's safe to use everywhere. However, the width and height attributes exist only in IE9+. You have to calculate them if you support IE8 and below:

var rect = $("#a")[0].getBoundingClientRect();

var width;
if (rect.width) {
  // `width` is available for IE9+
  width = rect.width;
} else {
  // Calculate width for IE8 and below
  width = rect.right - rect.left;
}

getBoundingClientRect is 70% faster than window.getComputedStyle in Chrome 28, and the differences are greater in Firefox: http://jsperf.com/getcomputedstyle-vs-getboundingclientrect


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...