相对于页面滚动背景 [英] Scroll Background Relative to Page

查看:71
本文介绍了相对于页面滚动背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次接触 Stack Overflow,如果我的问题有点冗长,我深表歉意.我有点困惑:

This is my first time on Stack Overflow, so I apologize if my question is a bit verbose. I have a bit of a quandary:

我想创建这种视差滚动效果,其中背景图像(其高度大于窗口的高度)始终与您在页面上的进度直接相关.

I want to create this parallax-scrolling effect where the background image (the height of which is larger than that of the window) always scrolls in direct relationship to your progress on the page.

例如,当您向下滚动页面 25% 时,背景图像应该滚动 25%.当您滚动到页面的最底部 (100%) 时,背景图片也应该滚动到其底部 (100%).

For example, when you've scrolled 25% of the way down the page, the background image should have scrolled by 25%. And when you've scrolled to the very bottom of the page (100%), the background image should have scrolled to its bottom as well (100%).

使用这种视差效果,背景图像仍会滚动,但不会平铺或需要拉伸.但是,使用我当前的代码(如下所示),背景确实滚动的速度比页面上的内容慢得多;但是它最终会到达背景的底部并开始平铺.

With this parallax effect, the background image would still scroll, but it wouldn't tile or need to be stretched. However, with my current code (show below), the background does scroll much at a much slower rate than the content on the page; however it eventually reaches the bottom of the background and starts tiling.

我觉得我在数学上遗漏了一些东西.有什么想法吗?

I feel like I'm missing something mathematically. Any ideas?

这是我正在使用的 jQuery:

注意:背景图片的高度为 1200 像素

$(window).scroll(function() {
    var x = $(this).scrollTop(); /* Scroll Position */
    var y = $('html').height(); /* Height of Page */
    var z = x / y; /* Progress of current position on page */
    $('html').css('background-position', '0% ' + (z * 1200) + 'px');
});

我发现了问题:正如您在到达视口底部之前不会开始滚动页面一样,在此之前我不应该开始滚动背景图像点.所以我现在需要的是一个新功能.如果 r 是视口高度,则该函数在向下滚动时不应将背景图像向下移动前 r 个像素,也不应向上移动背景图像向上滚动时的最后 r 个像素.男孩,这正在变成一个真正的视差滚动项目.有什么建议么?

I figured out the issue: Just as you don't start scrolling a page until you're at the bottom of the viewport, I shouldn't start scrolling the background image until that point either. So what I need now is a new function. If r is the viewport height, the function shouldn't move the background image down for the first r pixels when scrolling down, and it shouldn't move the background image up for the last r pixels when scrolling up. Boy, this is turning into a real parallax-scrolling project. Any suggestions?

推荐答案

我想这就是你想要的:

$(window).scroll(function() {
  var scrollPos = $(this).scrollTop();
  var pageHeight = $(document).height() - $(this).height();
  var progress = scrollPos / pageHeight;
  var backgroundOffset = (progress*100) + '%';
  $("html").css("background-position", "0% " + backgroundOffset);
});

查看演示

这篇关于相对于页面滚动背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆