开发者

Javascript timer using style.backgroundPosition Works fine in ff & chrome, not so lucky in IE

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("ti开发者_JS百科mer()",1000);
        }

This didn't work either, the counter remains static, can anyone shed any light on this issue? Many thanks in advance.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜