视差滚动:层之间不需要的间隙

时间:2018-01-17 19:44:36

标签: javascript html css web parallax

在我的网站here上,我使用CSS和Javascript实现了多层视差滚动。页面上下滚动,我有6层都在视差中移动。返回的每一层都以比前面的层略慢的速度滚动。

此实施有效,直到我点击右上角的汉堡菜单。

Image of the Bug

我不确定幻灯片菜单飞出后,为什么这些图层没有正确堆叠在一起。

以下是视差滚动的CSS:

.layer {
  background-position: bottom center;
  background-size: auto;
  background-repeat: no-repeat;
  width: 100%;
  height: 800px;
  position: fixed;
  z-index: -1;
}

.layer-bg {
  background-image: url("http://www.reynelee.com/wp-content/uploads/2017/12/layer1.png");
}

.layer-1 {
  background-image: url("http://www.reynelee.com/wp-content/uploads/2017/12/layer2.png\a     ");
  background-position: left bottom;
}

.layer-2 {
  background-image: url("http://www.reynelee.com/wp-content/uploads/2017/12/layer3.png");
}

.layer-3 {
  background-image: url("http://www.reynelee.com/wp-content/uploads/2017/12/layer4.png\a    ");
  background-position: right bottom;
}

这是JS:

(function() {
  window.addEventListener('scroll', function(event) {
    var depth, i, layer, layers, len, movement, topDistance, translate3d;
    topDistance = this.pageYOffset;
    layers = document.querySelectorAll("[data-type='parallax']");
    for (i = 0, len = layers.length; i < len; i++) {
      layer = layers[i];
      depth = layer.getAttribute('data-depth');
      movement = -(topDistance * depth);
      translate3d = 'translate3d(0, ' + movement + 'px, 0)';
      layer.style['-webkit-transform'] = translate3d;
      layer.style['-moz-transform'] = translate3d;
      layer.style['-ms-transform'] = translate3d;
      layer.style['-o-transform'] = translate3d;
      layer.style.transform = translate3d;
    }
  });

}).call(this);

HTML:

<div id='hero'>
  <div class='layer-bg layer' data-depth='0.10' data-type='parallax'></div>
  <div class='layer-1 layer' data-depth='0.20' data-type='parallax'></div>
  <div class='layer-2 layer' data-depth='0.50' data-type='parallax'></div>
  <div class='layer-3 layer' data-depth='0.80' data-type='parallax'></div>
  <div class='layer-overlay layer' data-depth='0.85' data-type='parallax'></div>
<!--   <div class='layer-4 layer' data-depth='0.90' data-type='parallax'></div> -->
  <div class='layer-logo layer' data-depth='0.95' data-type='parallax'> <a id='portfolio-button' href="http://www.reynelee.com/my-work/">View Work</a></div> <!-- my logo-->
<!--   <div class='layer-close layer' data-depth='1.00' data-type='parallax'></div> -->

</div>

1 个答案:

答案 0 :(得分:1)

问题是由transform css属性引起的。例如,如果您应用以下规则:

#page {
  transform: translateX(0);
}

如果没有打开菜单,您会注意到它会导致同样的问题。我以前遇到过这个问题而忘记了这个术语的实际名称,但是应用转换会导致浏览器以某种方式对待它。我的建议是在#page元素上应用此translateX(0),并根据此默认位置重新计算视差div的位置。我知道这不是一个完整的答案,但它应该让你去。