1

我使用了一个 javascript 在网站的首页标题中移动一个大背景图像来实现一个简单的动画。该脚本在 Mozilla 和 IE 中运行良好,但不知何故无法在 Chrome 中运行。请参阅以下内容:

        var scrollSpeed = 70;       // Speed in milliseconds
        var step = 1;               // How many pixels to move per step
        var left = 0;
        var top = 0;            // The current pixel row
        var imageHeight = 718;      // Background image height
        var headerHeight = 376;     // How tall the header is.

        //The pixel row where to start a new loop
        var restartPosition = -(imageHeight - headerHeight);

        function scrollBg(){

            //Go to next pixel row.
            left -= step;
            top -= step;

            //If at the end of the image, then go to the top.
            if (top == restartPosition){
                top += step
            }

            //Set the CSS of the header.
            $('#slideshow').css("background-position",left+"px"+" "+top+"px");
        }
        //Calls the scrolling function repeatedly
        var init = setInterval("scrollBg()", scrollSpeed);

我正在使用 jquery 1.4.3。html如下:

<div class="banner">
                        <div id="slideshow"></div>
                    </div>

如果有人能指出我在这里做错了什么,我将不胜感激。

4

1 回答 1

0

好的,我想通了。我只需将整个脚本包装在 $(document).ready 中,它就开始工作了。最终脚本如下:

$(document).ready(function() { 
        var scrollSpeed = 80;       // Speed in milliseconds
        var step = 1;               // How many pixels to move per step
        var left = 0;
        var top = 0;            // The current pixel row
        var imageHeight = 718;      // Background image height
        var headerHeight = 376;     // How tall the header is.

        //The pixel row where to start a new loop
        var restartPosition = -(imageHeight - headerHeight);

        function scrollBg(){

            //Go to next pixel row.
            left -= step;
            top -= step;

            //If at the end of the image, then go to the top.
            if (top == restartPosition){
                top += step
            }

            //Set the CSS of the header.
            $('#slideshow').css("background-position",left+"px"+" "+top+"px");
        }
        //Calls the scrolling function repeatedly
        setInterval(scrollBg, scrollSpeed);
    });
于 2012-04-23T05:27:06.163 回答