我想滚动背景图像直到结束像素,然后返回到图像的开头。我想不断重复这个序列。
我有一个代码,但它会在一个方向上连续滚动背景图像。
如何更改此代码以按我的意愿工作?
CSS:
body{margin:0; border:0; background:url(ejemplo3.jpg) repeat-x;}
HTML:
<body></body>
JQuery:
var scrollSpeed = 50;
// set the default position
var current = 0;
// set the direction
var direction = 'h';
function bgscroll() {
// 1 pixel row at a time
current -= 1;
// move the background with backgrond-position css properties
$('body').css("backgroundPosition", (direction == 'h') ? current + "px 0" : "0 " + current + "px");
}
//Calls the scrolling function repeatedly
setInterval(bgscroll, scrollSpeed);
最佳答案
当你有背景 repeat-x 时,它会进入一个循环,因此你会看到图像只在一个方向上旋转。但是,如果您将图像设置为不重复,那么您的代码可以修改如下所示:
/* 添加背景图片(评估你的图片)*/
body{margin:0; border:0; background:url(dsc01549.jpg) no-repeat;}
/* 添加脚本 */
// Global Variables
var scrollSpeed = 50;
// set the default position
var current = 0;
// image height & rotation complete
var _ht,_finishNRot=false;
// set the direction
var direction = 'h';
// create hidden image element to grab height of it for calculation purpose
var url = $('body').css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
var bgImage = $('<img />');
bgImage.hide().bind('load', function(){ _ht = $(this).height(); });
$('body').append(bgImage);
bgImage.attr('src', url);
function bgscroll() {
// while rotation not completed
if(_finishNRot==false){ current -= 1;} else {current+=1; } ;
// -ve Rotation completed
if(-(current)==_ht)_finishNRot = true;
// +ve Rotation completed
if((current)==0)_finishNRot = false;
// move the background with backgrond-position css properties
$('body').css("backgroundPosition", (direction == 'h') ? current + "px 0" : "0 " + current + "px");
}
//Calls the scrolling function repeatedly
setInterval(bgscroll, scrollSpeed);
希望对您有所帮助。
干杯, 阿肖克
关于jquery - 滚动背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22153896/