Reputation: 27862
If I assume that the background position will always be in the format:
0px 0px; or 10px 11px;
So, *number*px *number*px.
How can I get both the x position and the y position in Javascript?
Upvotes: 2
Views: 7875
Reputation: 253486
Given the following HTML:
<div id="demo"></div>
And CSS:
div {
height: 500px;
width: 500px;
margin: 0 auto;
background: #fff url(http://placekitten.com/300/300) 50% 50% no-repeat;
}
The following JavaScript works:
var demo = document.getElementById('demo'),
_tmp = window.getComputedStyle(demo,null).backgroundPosition.trim().split(/\s+/),
positions = {
'left' : _tmp[0],
'top' : _tmp[1]
};
console.log(positions, positions.left, positions.top);
The above approach does require a browser that supports window.getComputedStyle()
(obviously), and trim()
(though that could be replaced with a replace(/^\s+|\s+$/g,'')
).
To get access to the units, and numbers, independently I'd suggest creating other objects within the overall object to hold those numbers, and units:
var demo = document.getElementById('demo'),
_tmp = window.getComputedStyle(demo,null).backgroundPosition.trim().split(/\s+/),
positions = {
'left' : _tmp[0],
'top' : _tmp[1],
'numbers' : {
'left' : parseFloat(_tmp[0]),
'top' : parseFloat(_tmp[1])
},
'units' : {
'left' : _tmp[0].replace(/\d+/,''),
'top' : _tmp[1].replace(/\d+/,'')
}
};
console.log(positions, positions.left, positions.top, positions.numbers.left, positions.numbers.top, positions.units.left, positions.units.top);
As to what would happen if there was no background-position
set? Well, why not try that, with the following CSS:
div {
height: 500px;
width: 500px;
margin: 0 auto;
background-color: #fff;
background-image: url(http://placekitten.com/300/300);
background-repeat: no-repeat;
}
In Chromium it seems that you get the default background-position
of 0% 0%
(and corresponding numbers and units): JS Fiddle demo.
References:
String.parseFloat()
.String.replace()
.String.split()
.String.trim()
.window.getComputedStyle()
.Upvotes: 13