我正试图重现苹果iPhone 6s网页上的视差效果:点击
当你向上或向下滚动时,iPhone对象会有一个轻微的浮动视差动画。我想找到一种简单的方法来为我的网页上的多个对象重新创建它。我找到了ScrollMagic和Skrollr,但对于我想要实现的目标来说,它们似乎过于复杂。
例如,我该如何制作这些黑匣子的动画,以与iPhone相同的方式制作动画?
有人知道用HTML/CSS/JS快速实现这一点的方法吗?
谢谢你的帮助!
<div class="box1">
</div>
<div class="box2">
</div>
<div class="box3">
</div>
<div class="box4">
</div>
html{
height: 1500px;
width: 800px;
}
.box1{
position: relative;
background-color: black;
height: 150px;
width: 150px;
top: 260px;
left: 56%;
}
.box2{
position: relative;
background-color: black;
height: 150px;
width: 150px;
top: 360px;
left: 56%;
}
.box3{
position: relative;
background-color: black;
height: 150px;
width: 150px;
top: 260px;
left: 16%;
}
.box4{
position: relative;
background-color: black;
height: 150px;
width: 150px;
top: 320px;
left: 86%;
}
我的评论被调整了,所以我会再试一次。
以下代码可能会对您有所帮助。
$( window ).scroll(e=>{
// get scroll direction
let direction = 'down';
if ( this.oldScroll > this.scrollY ) direction = 'up';
this.oldScroll = this.scrollY;
animate('.box1', direction);
animate('.box2', direction, 3);
});
function animate( element, direction, speed, smooth ){
element = $( element )
speed = speed || 2;
smooth = smooth || 2;
// get element offset
let Y = parseInt( element.attr('data-y') || 0 );
// Calculate movement
if ( direction == 'down' ) Y = Y - (1*speed)
else Y = Y + (1*speed)
// Apply values
element.css({
'transition': smooth + 's transform',
'transform' : 'translateY(' + Y.toFixed(2) + 'px)',
})
// store new element offset
element.attr('data-y', Y)
}
您可以为窗口滚动上的每个元素执行函数。可以传递移动的速度和平滑度的值。
该函数计算移动并将transform: translateY()
和transition: 2s transform;
属性应用于元素。
我在code.actus.works/act-parallax 上有一个更完整的代码版本