我看过一个网站并开始考虑如何创建纸质火箭在立方体中移动的插图,如 https://www.atlassian.com/
网站。帮我用 CSS on scroll 来做。我尝试了以下代码但失败了。
$(function() {
var rotation = 0,
scrollLoc = $(document).scrollTop();
$(window).scroll(function() {
var newLoc = $(document).scrollTop();
var diff = scrollLoc - newLoc;
rotation += diff, scrollLoc = newLoc;
var rotationStr = "rotate(" + rotation + "deg)";
$(".plane").css({
"-webkit-transform": rotationStr,
"-moz-transform": rotationStr,
"transform": rotationStr
});
});
})
body {
overflow-x: hidden;
}
.container {
width: 100%;
height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="container">
<img class="plane" src="https://wac-cdn.atlassian.com/dam/jcr:db49283c-bf71-4ec4-b14c-fbc36a121b2f/plane-2.png?cdnVersion=ll" alt="" data-0="transform: translate3d(0px, 0px, 0)" data-1600="transform: translate3d(1600px, 200px, 0)" class="skrollable skrollable-between" style="transform: translate3d(228px, 28.5px, 0px);" width="168" height="36">
</div>
最佳答案
如果您希望飞机四处移动,而不是旋转,那么您可以使用 translate3d
代替或旋转。
$(function() {
function updateTranslation(el, x) {
const y = (Math.cos(x*0.015) * 50) + 100;
const tStr = `translate3d(${-x}px, ${y}px, 0px)`;
$(".plane").css({
"-webkit-transform": tStr,
"-moz-transform": tStr,
"transform": tStr
});
}
var translation = 0,
scrollLoc = $(document).scrollTop();
updateTranslation($(".plane"), 0);
$(window).scroll(function() {
var newLoc = $(document).scrollTop();
var diff = scrollLoc - newLoc;
translation += diff, scrollLoc = newLoc;
updateTranslation($(".plane"), translation);
});
})
body {
overflow-x: hidden;
}
.container {
width: 100%;
height: 1000px;
}
img {
position: fixed;
/* transition: transform 100ms ease;*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="container">
<img class="plane" src="https://wac-cdn.atlassian.com/dam/jcr:db49283c-bf71-4ec4-b14c-fbc36a121b2f/plane-2.png?cdnVersion=ll" alt="" width="168" height="36">
</div>
关于javascript - 如何在 Scroll 上使用 CSS 和 JS 创建插图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50704367/