且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我向下滚动时,如何让图像移动?

更新时间:2022-10-15 17:03:56

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]; //更新滚动事件的方块1和方块2的位置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;背景:红色; top:600px;}。square-2 {width:120px; height:120px;背景:黑色; left:800px;上一页:800px;}

 < div class =container id =container> < div class =square square-1>< / div> < div class =square square-2>< / div>< / div>  

b
$ b

希望能帮助你。

在这里你可以看到更多关于可移动元素和滚动事件的例子


Here is an example of what i want to achieve: https://www.flambette.com/en/

I have tried to change the css properties of images but that effect does not satisfy my needs. I have tried the following code:

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');
      }
}); 

This is supposed to move an image when you scroll between 10 and 200 px.

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>

Hope to help you.

Here you can see more examples about movable elements and scroll events.