gpt4 book ai didi

javascript - 向下滚动时如何使图像移动?

转载 作者:行者123 更新时间:2023-11-30 09:31:44 26 4
gpt4 key购买 nike

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

最佳答案

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

关于javascript - 向下滚动时如何使图像移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45822953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com