当我向下滚动页面时,我试图使该图像从左上角到右下角在屏幕上呈现动画。我真的很想让图像滚动得比页面慢,这样它就可以一直显示在屏幕上。我研究了视差,但不确定这是否是最好的解决方案。如果有办法让它一开始变小,然后向下滚动时变大,让它看起来从远处走近,那就加分了。
Here是该页面的链接,因为它现在正在工作以供引用:
HTML
<section class="astronaut">
<img src="assets/Images/astronaut_PNG69.png" alt="astronaut"
class="astronautImage">
</section>`
JavaScript
let current = $(window).scrollTop();
const total = $(window).height() - current;
const ele = $(".astronautImage");
const currPosition = ele.position().left;
const trackLength = 250;
$(window).scroll(function (event) {
current = $(window).scrollTop();
console.log({ total: total, current: current });
console.log(current / total * 100);
const newPosition = trackLength * (current / total)
ele.css({ left: currPosition + newPosition * (8) + 'px' });
});
最佳答案
使用 css 变换看起来更容易,并且会呈现您想要完成的平滑动画。这是一个帮助您入门的想法,只需应用一些百分比来缩放并翻译以使其保持一致
var measure = {
totalY: document.body.scrollHeight,
totalX: document.body.scrollWidth,
screenY: screen.height,
screenX: screen.width,
}
$(document).on('scroll', function() {
const posY = $(this).scrollTop();
const pos = {
x: measure.screenX / measure.totalY * posY + 'px',
y: posY + (measure.screenY / measure.totalY * posY) + 'px',
};
$('img').css('transform', `translate(${pos.x},${pos.y}) scale(${(1 + posY / measure.screenY)})`)
});
<div style="margin-bottom: 5000px;">
<img src="https://jonalden.github.io/JonAldenPortfolio/assets/Images/astronaut_PNG69.png" style="transform: translate(0, 0) scale(1);width: 100px;" />
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
要对 Angular 移动图像,您需要依赖 y 位置,因为您仅在页面中滚动 y。
更新了 fiddle :https://jsfiddle.net/m2uewboh/1/
关于javascript - 我可以在滚动时以对 Angular 线方式将该图像动画化到屏幕上,并且速度比窗口慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58018797/