Javascript 如何使用 jQuery 在 Firefox 中获取背景位置 y?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6821746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the background-position-y in firefox using jQuery?
提问by Stop Slandering Monica Cellio
$(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)?
在 chrome 上,即,和 safari 上,但不是 Firefox(我相信也不是 Opera)。你会认为 jQuery 会有一个 polyfill 但它没有,从 1.5 开始。如何轻松获得背景 Y 位置,例如背景动画(例如视差)?
EDIT: Tell Mozillayou want background-position-[x,y]
support. (use the "vote" feature, not comment, unless you have something prescient to add). Bug has been open since 2010 tho (3 years now) so don't hold your breath for a fix. :)
编辑:告诉 Mozilla你需要background-position-[x,y]
支持。(使用“投票”功能,而不是评论,除非您有先见之明要添加的内容)。错误自 2010 年以来一直开放(现在 3 年了)所以不要屏住呼吸寻求修复。:)
回答by Stop Slandering Monica Cellio
var backgroundPos = $(elem).css('backgroundPosition').split(" ");
//now contains an array like ["0%", "50px"]
var xPos = backgroundPos[0],
yPos = backgroundPos[1];
回答by Bob Fincheimer
Here is my hacky solution:
这是我的hacky解决方案:
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.
这y
将是一个数字,根据您的情况可以是百分比或像素偏移量。我做了一些正则表达式来去除非数字字符,这样你就可以将数字作为 javascript 数字获取。
回答by tknomad
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:
不幸的是,某些浏览器(例如 Chrome)将css('background-position')
或报告css('backgroundPosition')
为left <x> top <y>
,而其他浏览器(Internet Explorer、Firefox、Opera)将其报告为<x> <y>
. 以下对我有用:
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];
}
回答by Lawrence Chang
Building off sequoia mcdowell's answer you can also do
建立红杉麦克道威尔的答案,你也可以做
var yPos = $(elem).css('backgroundPositionY');