我有一个使用视差背景的网站,背景为1200px
长。
问题是:
我有一个不确定高度的页面,页面动态扩展到其内容。因此,如果用户按下阅读更多,它会在没有刷新的情况下展开,这会破坏视差效果,因为背景在页面完成之前到达其末尾。
背景是复杂的设计图像,它不能重复并添加背景色来掩盖白色空间不能完成,但我希望我能保持酷视差效果!
我的问题:
是否可以在视距到达特定的y位置时使视差停止,并在滚动到特定的y位置时冻结背景?但是当滚动回到特定的y位置以上时能够触发视差效果吗?
如果我们假设背景以0.1速度移动,那么最大高度将为1200/0.1 = 12000px
。
如果页面到达y-position = 12000px
- >停止视差效果并按原样冻结图像 - >如果页面返回1199px
再次开始视差
如何在Javascript中执行此操作?如果可能的话,CSS也会很棒。
修改
这是我在Stackoverflow上发布之前所做的:
我使用Stellar.js进行视差效果,只需添加以下javascript:
$(window).stellar({responsive:false});
并将以下代码添加到标记(包含背景图像):
<body data-stellar-background-ratio="0.1">
我还尝试了另一种方法,使用我在网络上找到的自定义JavaScript:
$( window ).scroll( function(){
var ypos = $( window ).scrollTop(); //pixels the site is scrolled down
var visible = $( window ).height(); //visible pixels
const img_height = 1261; //image height
var max_scroll = img_height - visible; //number of pixels of the image not visible at bottom
//change position of background-image as long as there is something not visible at the bottom
if ( max_scroll > ypos) {
$('body').css('background-position', "center -" + ypos + "px");
} else {
$('body').css('background-position', "center -" + max_scroll + "px");
}
});
在这种情况下,它会滚动直到背景结束,但我无法弄清楚如何减慢背景的滚动速度。