[英]Angular 4 smooth scroll within div
我试图在单击事件中在div内进行scrooling时创建平滑的滚动效果。 我可以使它工作,但无法正确配置它。
目的是创建一种轮播,当用户单击按钮右移时,只有包含轮播项目的div才会水平滚动。
但是,当我单击该按钮时,滚动太平滑了,大约需要2-3秒才能完成。
这是我的代码:
private parentEl;
ngOnInit() {
this.parentEl = document.getElementsByClassName('carousel_wrap');
}
public goRight(): void {
const el = this.parentEl[0];
const endPosition = el.scrollLeft + this.scrollFactor; // scrollFactor is the width of the child items on the carousel
let interval = setInterval(() => {
el.scrollLeft++;
if ( el.scrollLeft === endPosition ) {
clearInterval(interval);
}
});
}
如果我给setInterval一个延迟,例如setInterval(() => {...}, 16);
那么将需要更长的时间才能完成。
我期望的是例如以总共300毫秒执行整个动画。 有谁知道如何解决这个问题? 还是我做错了什么?
在setInterval
每一步中,您只添加了一个要滚动的像素。
您需要获得要滚动和除以时间的总距离(以像素为单位),因此您将获得速度(物理学,谁会想到的!?)
public goRight(): void {
const el = this.parentEl[0];
const endPosition = el.scrollLeft + this.scrollFactor; // scrollFactor is the width of the child items on the carousel
const time = 300;
const scrollVelocity = endPosition / time;
let interval = setInterval(() => {
el.scrollLeft += scrollVelocity;
if ( el.scrollLeft >= endPosition ) {
clearInterval(interval);
}
});
}
编辑:
正如我在评论中所说,我放了一点jsFiddle来展示如何通过结合使用CSS和scrollLeft来实现。 如果用户不需要滚动它,则scrollLeft部分甚至可能会被丢弃。
https://jsfiddle.net/y5m2xvzg/
简而言之,有一个带有overflow:hidden
的外部元素overflow:hidden
且固定大小。 在它的内部有一个内部元素,它将随着内容的增长而增长。 当您go()
,此内部元素将使用css进行动画处理。 完成后,正确设置了scrollLeft
和transform
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.