我使用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>
如果有人能指出我在这里做错了什么,真的很感激。
答案 0 :(得分: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);
});