开发者

How do I get the background-position-y in firefox using jQuery?

$(elem).css('backgroundPositionY')

does it on chrome, ie, and safari, but not Firefox (nor Opera I believe). You'd think jQuery would have a polyfill but it doesn't, as of 1.5. How can I easily get the background Y position for e.g. background animations (for e.g. parallax)?

EDIT: Tell Mozilla you want background-position-[x,y] support. (use the "vote" feature, not comment, unless you have somet开发者_运维技巧hing prescient to add). Bug has been open since 2010 tho (3 years now) so don't hold your breath for a fix. :)


var backgroundPos = $(elem).css('backgroundPosition').split(" ");
//now contains an array like ["0%", "50px"]

var xPos = backgroundPos[0],
    yPos = backgroundPos[1];


Here is my hacky solution:

var $jQueryObject = jQuery('#jQueryObject');
var backgroundPosition = $jQueryObject.css('background-position');
// backgroundPosition = "0% 0%" for example
var displacement = backgroundPosition.split(' '); // ["0%", "0%"]
var y = Number(displacement[1].replace(/[^0-9-]/g, ''));

// As suggested, you could also get the float:
var yFloat = parseFloat(displacement[1].replace(/[^0-9-]/g, ''));

Here y would be a number that would either be the percent or pixel offset depending on your situation. I did a little regex to get rid of the non-number characters so you can get the number as a javascript Number.


Unfortunately, some browsers (such as Chrome) report css('background-position') or css('backgroundPosition') as left <x> top <y>, while others (Internet Explorer, Firefox, Opera) report it as <x> <y>. The following worked for me:

var x, y, pos = $(elem).css('background-position').split(' ');

if(pos[0] === 'left') {
  x = pos[1];
  y = pos[3];
} else {
  x = pos[0];
  y = pos[1];     
}


Building off sequoia mcdowell's answer you can also do

var yPos = $(elem).css('backgroundPositionY');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜