【问题标题】:Parallax based on mousemove has different offset基于 mousemove 的视差有不同的偏移量
【发布时间】:2017-05-05 13:51:16
【问题描述】:

如何在所有部分中获得相同的视差偏移?现在,随着您添加更多sections,偏移量会增加。请注意,在.two.three 部分中,视差与.one 部分不同。我希望.two.three 部分具有与.one 部分相同的视差。我不确定是什么导致 .two.three 部分中的 div 变宽。

为什么会发生这种情况,我该如何解决?

JSFiddle

提前谢谢你。

JS

var currentX = '';
var currentY = '';
var movementConstant = .05;

$(document).mousemove(function(e) {
    var xToCenter = e.pageX - window.innerWidth/2;
    var yToCenter = e.pageY - window.innerHeight/2;

    $('.parallax div').each( function(i) {
      var $el = $(this);
      var newX  = (i + 1) * (xToCenter * movementConstant);
      var newY = (i + 1) * (yToCenter * movementConstant);      
      $el.css({left: newX + 'px', top: newY + 'px'});
    });
});

HTML

<section class="one">
  <div class="parallax">
      <div class="asset asset-layer4">4</div>
      <div class="asset asset-layer3">3</div>
      <div class="asset asset-layer2">2</div>
      <div class="asset asset-layer1">1</div>
  </div>
</section>
<section class="two">
  <div class="parallax">
      <div class="asset asset-layer4">4</div>
      <div class="asset asset-layer3">3</div>
      <div class="asset asset-layer2">2</div>
      <div class="asset asset-layer1">1</div>
  </div>
</section>
<section class="three">
  <div class="parallax">
      <div class="asset asset-layer4">4</div>
      <div class="asset asset-layer3">3</div>
      <div class="asset asset-layer2">2</div>
      <div class="asset asset-layer1">1</div>
  </div>
</section>

CSS

.one,
.two,
.three {
  position: relative;
  width: 100%;
  height: 200px;
}

.one { background-color: pink; }
.two { background-color: lightgray; }
.three { background-color: orange; }

.parallax {
    position: absolute;
    left: 50%;
    top: 50%;
    bottom: 50%;
    right: 50%;
    overflow: visible;
}
.asset {
    position: absolute;
}
.asset-layer1 {
    background-color: yellow;
}
.asset-layer2 {
  background-color: green;
}
.asset-layer3 {
  background-color: blue;
}
.asset-layer4 {
  background-color: red;
}
body {
  overflow:hidden;
}

【问题讨论】:

    标签: javascript parallax mousemove


    【解决方案1】:

    问题是您正在对 .parallax 的子 div 执行 each over ALL。这意味着您循环了大约 11 次。每次乘以更大的 i 值,它就会开始消失。

    相反,我所做的是在每个 Parallax 容器中,您将遍历它的子容器,为您提供 0-3 之间的值。现在它们同步了!

    https://jsfiddle.net/p4hrbdge/2/

       $('.parallax').each( function(i) {
            $(this).find('div').each(function(i) {
            var $el = $(this);
            var newX  = (i + 1) * (xToCenter * movementConstant);
            var newY = (i + 1) * (yToCenter * movementConstant);    
            $el.css({left: newX + 'px', top: newY + 'px'});
            })
        });
    

    【讨论】:

    • 谢谢!这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多