jquery - 滚动背景图像

标签 jquery css

我想滚动背景图像直到结束像素,然后返回到图像的开头。我想不断重复这个序列。

我有一个代码,但它会在一个方向上连续滚动背景图像。

如何更改此代码以按我的意愿工作?

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/

相关文章:

javascript - 大图片无法上传Ajax/Jquery,FormData为空

javascript - 如何让固定滚动的 div 与窗口的其余部分一起滚动?

Mouseleave 事件上的 Javascript setTimeout

javascript - 使用 jQuery 在单击时叠加在图像上

javascript - 如何通过双击操作将光标(插入符号)放入标签中?

javascript - 将选定的选项复制到另一个选择

asp.net - jquery 验证特定按钮 onclick

html - flex 容器宽度适合内容宽度

css - 从一个自定义标签生成多个 html 标签

css - 带有无序列表的 Flexbox