向下滚动时如何移动图像?

时间:2017-08-22 16:37:26

标签: javascript html css web

这是我想要实现的一个例子: https://www.flambette.com/en/

我曾尝试更改图片的css属性,但这种效果无法满足我的需求。 我尝试了以下代码:

mydocument.on('scroll',function() {
      if (mydocument.scrollTop() > 10 && mydocument.scrollTop() < 200 ) {
         $('#first').css('top', '320px');
         $('#first').css('left', '215px');
         $('#first').css('transition', '0.5s');
      } 
      else {
         $('#first').css('top', '300px');
         $('#first').css('left', '200px');
         $('#first').css('transition', '0.5s');
      }
}); 

当您在10到200像素之间滚动时,这应该会移动图像。

1 个答案:

答案 0 :(得分:3)

&#13;
&#13;
var container = document.getElementById('container');
var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
var scrollArea = 1000 - windowHeight;
var square1 = document.getElementsByClassName('square')[0];
var square2 = document.getElementsByClassName('square')[1];

// update position of square 1 and square 2 when scroll event fires.
window.addEventListener('scroll', function() {
  var scrollTop = window.pageYOffset || window.scrollTop;
  var scrollPercent = scrollTop/scrollArea || 0;

  square1.style.left = scrollPercent*window.innerWidth + 'px';
  square2.style.left = 800 - scrollPercent*window.innerWidth*0.6 + 'px';
});
&#13;
body {
  overflow-x: hidden;
}

.container {
  width: 100%;
  height: 1000px;
}

.square {
  position: absolute;
}

.square-1 {
  width: 100px;
  height: 100px;
  background: red;
  top: 600px;
}

.square-2 {
  width: 120px;
  height: 120px;
  background: black;
  left: 800px;
  top: 800px;
}
&#13;
<div class="container" id="container">
  <div class="square square-1"></div>
  <div class="square square-2"></div>
</div>
&#13;
&#13;
&#13;

希望能帮到你。

Here you can see more examples关于可移动元素和滚动事件。