问题描述
我有一些文本元素应该根据滚动位置在其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