【问题标题】:How do I make an image move when i scroll down?向下滚动时如何使图像移动?
【发布时间】:2017-08-22 16:37:25
【问题描述】:

这是我想要实现的示例: 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 像素之间滚动时,这应该会移动图像。

【问题讨论】:

标签: javascript html css web


【解决方案1】:

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';
});
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;
}
<div class="container" id="container">
  <div class="square square-1"></div>
  <div class="square square-2"></div>
</div>

希望能帮到你。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多