本篇文章给大家介绍js如何实现dom元素横向、纵向滚动的动画,希望对需要的朋友有所帮助!
通过settimeout实现的滚动动画,支持反复点击变快
支持水平滚动和竖直滚动,快速点击会将上次未滚动完的距离叠加,滚动的时间不变,滚动的速度会变快
使用方式
1、复制下方代码;
2、导出对应的方法 movingcolumn - 竖直滚动 moving--水平滚动
3、函数接收3个参数 dom: 要滑动的元素 space: 点击一次要滚动的距离 istop/isleft 是否向上/左滚动
功能修改
const hz = 60 在规定时间分几次滚动到目标位置 60是人肉眼可识别的刷新率
每次滚动的时间为 settime里的1ms * hz = 60ms
let timer:any = null // 定时器let targetlocation = -1 // 上一次点击应该滚动到的目标位置let toltalspace = 0 // 本次要滚动的距离/** * @info 竖直滚动 * @info 滚动动画 hz 刷新率 可以修改滚动的速度 * @params dom:要滚动的元素; space 要滚动的距离; istop 滚动的方向;*/const movingcolumn = (dom:htmldivelement, space: number, istop:boolean) => { // 用户快速点击 则把上次未滚动的距离与本次滚动结合再一起 if (timer && targetlocation !== -1) { toltalspace += targetlocation - dom.scrolltop // 计算本次的目标距离 if(istop) { targetlocation = dom.scrolltop + toltalspace + space } else { targetlocation = dom.scrolltop + toltalspace - space } } else if (!timer) { toltalspace = 0 targetlocation = -1 } if (istop) { toltalspace -= space } else { toltalspace += space } // 获取本次的目标位置 const position = dom.scrolltop targetlocation = position + toltalspace clearinterval(timer) timer = null const hz = 60 let i = 1 timer = setinterval(() => { dom.scrolltop = position + i * toltalspace / hz ++i if (i >= hz) { clearinterval(timer) timer = null dom.scrolltop = targetlocation // 位置修正 toltalspace = 0 targetlocation = -1 } }, 1)}/** * @info 水平滚动 * @info 滚动动画 hz 刷新率 可以修改滚动的速度 * @params dom:要滚动的元素; space 要滚动的距离; isleft 滚动的方向;*/const moving = (dom:htmldivelement, space: number, isleft:boolean) => { // 用户快速点击 则把上次未滚动的距离与本次滚动结合再一起 if (timer && targetlocation !== -1) { toltalspace += targetlocation - dom.scrollleft // 计算本次的目标距离 if(isleft) { targetlocation = dom.scrollleft + toltalspace + space } else { targetlocation = dom.scrollleft + toltalspace - space } } else if (!timer) { toltalspace = 0 targetlocation = -1 } if (isleft) { toltalspace -= space } else { toltalspace += space } // 获取本次的目标位置 const position = dom.scrollleft targetlocation = position + toltalspace clearinterval(timer) timer = null const hz = 60 let i = 1 timer = setinterval(() => { dom.scrollleft = position + i * toltalspace / hz ++i if (i >= hz) { clearinterval(timer) timer = null dom.scrollleft = targetlocation // 位置修正 toltalspace = 0 targetlocation = -1 } }, 1)}export { moving, movingcolumn}
相关推荐:【javascript视频教程】
以上就是实例讲解js如何实现dom元素横向及纵向滚动的动画的详细内容。