2017-08-22 108 views
1

这里是什么,我想实现一个例子: 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 PX之间滚动移动的图像。

+0

是这样的? https://jsfiddle.net/yaLz1zqz/1/ – Stuart

+0

@Stuart你确定它是正确的链接? – Ivan

+0

糟糕 - https://jsfiddle.net/ashjffcz/ – Stuart

回答

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关于可移动元素和滚动事件。

+1

嘿谢谢杰夫! –

+0

没问题,男人! :) –

相关问题