我正在尝试制作一个jQuery动画,它会滚动背景图像,直到它到达图像的末尾,然后重新开始。
我设法让滚动工作&通过混合来自这里的各种代码来计算背景图像的高度,但是当我尝试将它们组合时它停止工作。
我不是家庭用javascript,所以不知道发生了什么!
以下代码:
<div class="animateIcon">
<img src="images/spacer.png" width="144" height="167" class="animation" />
</div>
的jQuery
$(document).ready(function () {
var scrollSpeed = 100;
var current = 0;
var step = 167; // How many pixels to move per step
var direction = 'v';// set the direction
$.fn.getBgImage = function (callback) {
var height = 0;
var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
var tempImg = $('<img />');
tempImg.hide(); //hide image
tempImg.bind('load', callback);
$('body').append(tempImg); // add to DOM before </body>
tempImg.attr('src', path);
$('#tempImg').remove(); //remove from DOM
};
$(".animation").getBgImage(function () {
var restartPosition = -($(this).height());
});
function bgscroll() {
//Go to next pixel row.
current -= step;
//If at the end of the image, then go to the top.
if (current <= restartPosition) {
current = 0;
}
// move the background with backgrond-position css properties
$('.animation').css("background-position", (direction == 'v') ? "0 " + current + "px" : current + "px 0");
}
//Calls the scrolling function repeatedly
setInterval(bgscroll, scrollSpeed);
});
当我添加此代码时,它似乎会中断,但无法找出原因:
//If at the end of the image, then go to the top.
if (current <= restartPosition) {
current = 0;
}
任何帮助表示赞赏!
答案 0 :(得分:1)
我没有尝试过运行代码,但看起来restartPosition
与bgscroll
的范围不同。
尝试在顶部添加var restartPosition;
与其他全局变量,并将var restartPosition = -($(this).height());
更改为restartPosition = -($(this).height());