使用 style.backgroundPosition 的 Javascript 计时器在 ff & 中工作正常chrome,在 IE 中就没那么幸运了
我在 js 中制作了一个非常简单的倒计时器,它从数组中获取值并将它们应用于元素 background-position
属性(这根据 的值显示图像的不同部分curS
)。
这是代码:
window.onload = timer;
var curS = 5;
function timer(){
var bgP = new Array("0 -1px","0 -22px","0 -45px","0 -67px","0 -89px");
if (curS <= 5){
document.getElementById("count").style.backgroundPosition = bgP[curS];
}
curS--;
setTimeout("timer()",1000);
}
这适用于 FF、Chrome、Opera 等,但不适用于 IE 7/8。我知道 IE 对旧的背景位置有点不确定,并且读到它更喜欢 background-position-x
& background-position-y
所以我将以下代码放置在 IE 中(仅限条件):
window.onload = timer;
var curS = 5;
function timer(){
var bgPx = 0;
var bgPy = new Array("-1px","-22px","-45px","-67px","-89px");
if (curS <= 5){
document.getElementById("count").style.backgroundPositionX = bgPx;
document.getElementById("count").style.backgroundPositionY = bgPy[curS];
}
curS--;
setTimeout("timer()",1000);
}
这也不起作用,计数器保持静态,任何人都可以解释这个问题吗?非常感谢。
I have made a very simple countdown timer in js that takes values from an array and applies them to an elements background-position
property(this displays a different part of an image dependant on the value of curS
).
Here's the code:
window.onload = timer;
var curS = 5;
function timer(){
var bgP = new Array("0 -1px","0 -22px","0 -45px","0 -67px","0 -89px");
if (curS <= 5){
document.getElementById("count").style.backgroundPosition = bgP[curS];
}
curS--;
setTimeout("timer()",1000);
}
This works in FF,Chrome, Opera etc but not in IE 7/8. I am aware that IE is a bit iffy on the old background-position and have read that it prefers background-position-x
& background-position-y
So I placed the following code within an IE only conditional:
window.onload = timer;
var curS = 5;
function timer(){
var bgPx = 0;
var bgPy = new Array("-1px","-22px","-45px","-67px","-89px");
if (curS <= 5){
document.getElementById("count").style.backgroundPositionX = bgPx;
document.getElementById("count").style.backgroundPositionY = bgPy[curS];
}
curS--;
setTimeout("timer()",1000);
}
This didn't work either, the counter remains static, can anyone shed any light on this issue? Many thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题是数组索引:你从 5 开始,而你应该从 4 开始。当你尝试将 style.backgroundPosition 设置为 undefined 时,Chrome 会忽略它,但 IE 会抛出“无效参数”。
虽然我在这里,但我还想指出,在 javascript 中将函数编写为字符串几乎是不可能的。您的超时应该是
setTimeout(timer,1000)
,使用直接函数引用而不是字符串。Your problem is array indices: you're starting at 5 where you should be starting at 4. Chrome ignores it when you try to set style.backgroundPosition to undefined, but IE throws "Invalid argument.".
While I'm here, I'd like to point out also that it's pretty much never okay to write functions as strings in javascript. Your timeouts should be
setTimeout(timer,1000)
, using a direct function reference rather than a string.