Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the top left coordinates of a background image that is shifted with CSS

I am trying to find the top and left coordinates of a background-image that by applying some CSS rules has been shifted off the viewport. Difficult to explain in words, here is a visual example:

Background-image shifted to the left

Black box: Viewport
Red box: <div> with a background-image
Blue box: <div> containing an <a>

When I do getBoundingClientRect of the <div> with the background-image, I get 0px 0px. It makes sense, because the container is within the viewport, and it starts at the very top and left.

However, the background-image of that <div> has been shifted to the left (and it could have been shifted to the top too), and therefore the coordinates should differ from the ones from the <div>. So my question is:

How would I READ (I don't want to change) How can I find the coordinates of the green point in any page that is facing this situation? I mean, the browser must have known how many pixels it needs to cut the background-image, right?

I am currently using Javascript to access the Web/Dom API. I am willing to use anything (undocumented maybe?) to achieve this.

like image 674
Nobita Avatar asked Nov 21 '13 18:11

Nobita


1 Answers

Here is a solution to your problem that works on modern browsers.

var testNode = document.getElementById('test');
var testBackgroundPosition = getComputedStyle(testNode,null).backgroundPosition.replace(/px/g,'').split(' ');

As you can see from the following page not all web browsers support this method.

http://caniuse.com/getcomputedstyle

There is no answer to the "Cross-browser (IE8-) getComputedStyle with Javascript?" question yet and I don't know another solution to this problem.

Without getComputedStyle() there is no reasonable way of getting the current style settings for an element since that requires going through all of the included CSS. It is possible but involves CPU intensive code. If you were to go that direction you will be able to create a temporary div inside the existing div with relative positioning, possibly setting top and left, or margins, to the values from the background position and then calculate where the div's clientTop and clientLeft ends up which may work in some cases.

like image 198
Ralph Ritoch Avatar answered Sep 26 '22 03:09

Ralph Ritoch