窗口上的jQuery滚动动画背景图像位置

我试图使用jQuery实现滚动效果。 我有一个背景div设置为100%浏览器窗口大小,隐藏溢出。 这有一个大的背景图像约。 1500px x 2000px。

我想要的效果是当用户向下滚动页面时,背景图像以滚动距离的百分比移动,因此对于每页向下滚动200px,图像在相同方向上移动10px。

谁能指出我正确的方向? 这有可能吗? : ) 提前谢谢了。

UPDATE

我已经尝试了@Capt Otis的建议的变化,但我仍然在努力解决我正在玩的代码如下:

$(window).scroll(function(){ if($(this).scrollTop() > 200) { $('#div').animate({'background-postion': '+=10px 0'}, 500); } }); 

任何人都可以解释我做错了什么吗?

干得好。 背景设置为10%滚动。 您可以通过更改代码中的10来更改背景滚动速率。

CSS

 html, body{ height:100%; min-height:100%; margin:0; padding:0; } .bg{ width:100%; height:100%; background: #fff url(..) no-repeat fixed 0 0; overflow:auto; } 
..

JavaScript的

 $('.bg').scroll(function() { var x = $(this).scrollTop(); $(this).css('background-position', '0% ' + parseInt(-x / 10) + 'px'); }); 

查看http://jsfiddle.net/Vbtts/上的工作示例
单击此链接以获取全屏示例: http : //jsfiddle.net/Vbtts/embedded/result/


这对我有用:

在js中:

 $(window).scroll(function() { var x = $(this).scrollTop(); $('#main').css('background-position', '100% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 2) + 'px, center top'); }); 

在css中:

 #main { background: url(../img/img1.png) center top no-repeat, url(../img/img2.png) center top no-repeat, url(../img/img3.png); background-repeat: no-repeat, no-repeat, repeat-x; background-position: right top, left top, center top; 

其中#main是我想要移动的背景图像的div。 没有必要高度:100%的HTML,身体。

这是多个背景图像的变体。

如果你不想被额外的背景div所困扰,这里是我的代码,我从几个例子中得到了解释:

 $(window).scroll(function () { setBackgroundPosition(); }) $(window).resize(function() { setBackgroundPosition(); }); function setBackgroundPosition(){ $("body").css('background-position', "-" + (1920 - $(window).width()) / 2 + "px " + -(Math.max(document.body.scrollTop, document.documentElement.scrollTop) / 4) + "px"); } 

跨浏览器问题需要Math.max。 同时用背景图像的宽度替换“1920”

 body{ background-image:url(images/background.jpg); background-position:center top; background-repeat:no-repeat; background-attachment:fixed; } 

这可能会这样做:

 $(window).scroll(function(){ $('#div').css("background-position",parseInt($(this).scrollTop()*0.05)); }) 

在这里查看用户在页面上滚动了多远的示例。 看到$(this).scrollTop()

而不是引用$(this),尝试使用背景div。 然后使用.scroll函数确定移动背景的程度。

您的代码应该看起来像这样:

 $("html").scroll(function{ var move["bottom"] = $("bg_div").scrollTop(); $("bg_div").animate({bottom: move}, 500); }); 

当你在CSS中有两个部分时,我认为你不能使用+ =或 – =。 有一些你可以做的,它有点棘手,但它的工作原理:

 $(window).scroll(function(){ if($(this).scrollTop() > 200) { var bgpos = $("#div").css("background-position"); var bgposInt = 0; if(bgpos.indexOf("px")!=-1) { bgpos = bgpos.substr(bgpos.indexOf("px")+3); bgposInt = parseInt(bgpos.substr(0, bgpos.indexOf("px"))); } bgposInt += 10; $("#div").animate({"background-position": "0 "+bgposInt+"px"}, 500); } }); 

此代码仅从div的背景位置(顶部位置)获取第二个数字,将其转换为int,并将其增加10.然后它只将div设置为新位置的动画。