开发者

How can you find a backgound image y-offset using javascript?

Pretty straight forward I suppose. Getting the background position is easy, but just getting the Y position seems to be a bit tougher. Do I have to splice up the background position output开发者_JAVA技巧? Or is there a cleaner way of getting the value?

EDIT: I was able to get this, the javascript version of Damien-at-SF's answer, but for some reason yResult returns '(an empty string)' when I do a console.log() for it.I don't think it's actually grabbing the value. What am I doing wrong?

var yResult = document.getElementById('sub-image1').style.backgroundPosition;
var a = yResult.split(" ");
var y = parseFloat(a[1]);


You could use jQuery for wide browser support:

//returns y position of background image
$("#example").css("background-position").split(' ')[1]

Working example here: http://jsfiddle.net/QagqS/

That example alerts the y position of the background image :)

UPDATE WITHOUT JQUERY:

For standard javascript ( http://jsfiddle.net/QagqS/3/ ), you need to define your css inline, within the element:

<div id="example" style="background-position:10px 100px"></div>

This allows the javascript to pick up on the style of the element and as such you can use the

document.getElementById('example').style.backgroundPosition.split(' ')[1]

method posted above...


You could use <element>.style.backgroundPositionY, but i am unsure how widely supported it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜