Javascript滚动视差定位

Javascript Scrolling Parallax Positioning

我目前正在制作 javascript 视差页面。我设法设置了背景图片和其他 2 张图片(#content、#content2)。

当我一直向下滚动到我的内容然后到我的内容 2 时,我希望我的网页到此结束。但是我可以无限向下滚动。

任何人都可以看看我的代码并告诉我我需要添加或更改什么,以便我的网页在 content2 之后结束并停止滚动。

请注意,我的#image 是我的主要背景,content 和 content2 是覆盖我背景的单独图像,但我希望我的页面和滚动停止在 content2。

代码:

<style type="text/css">
    * {
        margin: 0px;
        padding: 0px;
    }
    #image {
        position: relative;
        z-index: -1
    }
    #content {
        height:690px;
        width: 100%;
        margin-top:-10px;
        background:url(http:/chicago_bulls_wallpaper_backgrounds.jpg);
        position: relative;
        z-index: 1; 
        background-repeat:   no-repeat;
        background-position: center center;
    }

    #content2 {
        top:710px;
        height:570px;
        width: 100%;
        margin-top:-10px;
        background:url(All.jpg);
        position: relative;
        z-index: 1; 
        background-repeat:   no-repeat;
      background-position: center center
         }

      </style>
    <script type="text/javascript">
    var ypos, image;
    function parallex() {
        ypos = window.pageYOffset;
        image = document.getElementById('image');
        image.style.top = ypos * 1 + 'px';
    }
    window.addEventListener('scroll', parallex);
    </script>
     <img id="image" src="black-glass.png" height="710px" width="100%" />
   <div id="content"></div>
    <div id="content2"></div>

这样的东西是你想要的吗?我没有无限滚动的问题。

http://codepen.io/vinsongrant/pen/advzww

<img id="image" src="https://upload.wikimedia.org/wikipedia/commons/d/da/The_City_London.jpg" height="710px" width="100%" />

<div id="content">
  <h1>Here is content 1</h1>
</div>

<div id="content2">
  <h1>Here is content 2</h1>
</div>

这是因为您的视差系数是 1,这意味着背景完全随屏幕移动。因此,浏览器认为它总是有空间并且总是可以向下滚动,这实际上是一个非常滑稽的错误。

如果您想要真正的视差滚动,请将您的因子设置为小于 1,如下所示:

image.style.top = ypos * 0.95 + 'px';

如果您根本不想让您的背景随页面的其余部分一起移动,请将主体的背景设置为此图像(就像您已经对 div 所做的那样),然后设置 background-attachment 属性 到 fixed - 不需要 JavaScript。