如何解决根据滚动位置向变量计算添加缓动
我有一些文本元素应该根据滚动位置在其x轴上移动。 请参阅此笔作为参考:
https://codepen.io/magglomag/pen/GRZwRNB
HTML
<h1 class="moving-text-wrapper">
<div class="moving-text moving-text-1" data-scroll-speed="-4">Lorem</div>
<div class="moving-text moving-text-2" data-scroll-speed="2">ipsum</div>
<div class="moving-text moving-text-3" data-scroll-speed="9">sonsetetur</div>
<div class="moving-text moving-text-4" data-scroll-speed="-6">sit</div>
<div class="moving-text moving-text-5" data-scroll-speed="3">amet</div>
</h1>
CSS
html {
height: 300vh;
}
.moving-text-wrapper {
margin-top: 100vh;
text-align: center;
}
jQuery
$.fn.moveIt = function(){
var $window = $(window);
var instances = [];
$(this).each(function(){
instances.push(new moveItItem($(this)));
});
window.addEventListener('scroll',function(){
var scrollTop = $window.scrollTop();
var elemOffsetTop = $( '.moving-text-wrapper' ).offset().top;
var translateX = elemOffsetTop - scrollTop - $( window ).height()/2;
instances.forEach(function(inst){
inst.update(translateX);
});
},{passive: true});
}
var moveItItem = function(el){
this.el = $(el);
this.speed = parseInt(this.el.attr('data-scroll-speed'));
};
moveItItem.prototype.update = function(translateX){
this.el.css('transform','translateX(' + -(translateX / this.speed) + 'px)');
};
$(function(){
$('[data-scroll-speed]').moveIt();
});
我要添加的变量translateX
稍微放松一点,所以当滚动停止时,文本将移动更长一点,并且不会像当前的笔一样直接停止。
有人提示如何解决吗? 非常感谢!
解决方法
实际上,使用CSS过渡很容易解决这个问题:
我刚刚向这样的元素添加了过渡:
.moving-text {
transition-property: transform;
transition-duration: 1s;
transition-timing-function: ease-out;
}
请参阅更新的Codepen以获取参考: https://codepen.io/magglomag/pen/YzqRPoX
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。