我需要有关 translate-animate 属性的帮助。 当我在页面上向下滚动时,我想向上翻译一张图片。 现在我知道我可以使用属性 translateY(px) 来移动它,但是我不知道如何在滚动时进行 translateY。 我想让我的网页看起来像这样
https://www.apple.com/uk/iphone/
如您所见,当您向下滚动时,图像会平滑地向上平移。 我需要一个代码,这样我就可以在向下滚动时平滑地向上翻译我的图像。
P.s-这是我的第一个问题,如果我不清楚,请见谅。
最佳答案
这是我自己制作的相当便宜的视差效果,但不需要任何特殊魔法即可工作... Link to my original demo page
let $scrollPrev = 0;
const $viewBottom = () => $(window).scrollTop() + $(window).innerHeight(),
$parallaxIllusion = () => {
const $pxTop = $(".parallaxTop"),
$pxMid = $(".parallaxMiddle"),
$pxBottom = $(".parallaxBottom"),
$scrollCurr = $viewBottom(),
$bodyTop = $("body").offset().top,
$bodyBottom = $bodyTop + $("body").outerHeight(true),
$pxspeed = $scrollCurr - $bodyTop;
if ($bodyTop > 0 && $viewBottom() > $bodyTop && $(window).scrollTop() <= $bodyBottom) {
$pxTop.css({
"top": 40 + -$pxspeed / 4
});
$pxMid.css({
"top": $pxspeed / 2
});
$pxBottom.css({
"top": ($pxspeed / 4)
});
$scrollPrev = $scrollCurr;
};
};
$(document).ready(() => {
$(window).scroll(() => {
$parallaxIllusion();
});
});
body{
height:700px;
}
.parallaxTop {
background: url('https://raw.githubusercontent.com/NightKn8/pure/master/img/demo1/pxHand.png') center center / cover no-repeat;
position: absolute;
left: 50%;
-ms-transform: translate(-100%, 0);
-webkit-transform: translate(-100%, 0);
transform: translate(-100%, 0);
width: 403px;
height: 298px;
z-index: 2;
}
.parallaxMiddle {
background: url('https://raw.githubusercontent.com/NightKn8/pure/master/img/demo1/pxCaps.png') center center / cover no-repeat;
position: absolute;
right: 50%;
-ms-transform: translate(50%, 0);
-webkit-transform: translate(50%, 0);
transform: translate(50%, 0);
width: 109px;
height: 117px;
z-index: 4;
}
.parallaxBottom {
background: url('https://raw.githubusercontent.com/NightKn8/pure/master/img/demo1/pxBeer.png') center center / cover no-repeat;
position: absolute;
right: 50%;
-ms-transform: translate(100%, 0);
-webkit-transform: translate(100%, 0);
transform: translate(100%, 0);
width: 406px;
height: 443px;
z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="parallaxTop"></div>
<div class="parallaxMiddle"></div>
<div class="parallaxBottom"></div>
</body>
请注意,您可以编辑代码以峰值 1 图像。速度或方向控制在 if
级别。
关于javascript - 在 jquery 中滚动翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44269125/