Reputation: 27012
The function getBoundingClientRect()
can return non-integer values. For example, something like:
<div style="position: relative; left: 5%; width: 66.666%"></div>
almost always have non-integer values for the left
and width
values of getBoundingClientRect
. You can see this at http://plnkr.co/edit/QW91gy3hPMagSECQswdM?p=preview , with an example value of its left value being 32.796875 (in Chrome at least).
How these non-integer values are actually rendered on the screen I believe is browser-dependent.
So, how can I programatically find the whole-pixel coordinates of an element on-screen?
Edit: ideally without jQuery, and ideally without walking the DOM.
Upvotes: 1
Views: 749
Reputation: 2615
a lot of modern browsers use subpixel rendering, so most likely there exist no whole-pixel coordinates..
but with jQuery you can do something like this to get an array [left, top, width, height] relative to document space:
function bounds(el) {
var $el = $(el);
if (!$el.is(':visible')) {
return null;
}
var offset = $el.offset();
return [offset.left, offset.top, $el.outerWidth(), $el.outerHeight()];
}
relative to Viewport:
function boundsVp(el) {
var $el = $(el);
if (!$el.is(':visible')) {
return null;
}
var $win = $(window);
var offset = $el.offset();
return [offset.left - $win.scrollLeft(), offset.top - $win.scrollTop(), $el.outerWidth(), $el.outerHeight()];
}
you might be interested in jQuery.fracs as well..
Upvotes: 1