类别:react / 日期:2023-05-04 / 浏览:666 / 评论:0
简单来说,无缝轮播的核心是制造一个连续的效果。最简单的方法就是复制一个轮播的元素,当复制元素将要滚到目标位置后,把原来的元素进行归位的操作,以达到无缝的轮播效果。
贴一段轮播的核心代码:
// scroll the notice
useEffect(() => {
const requestAnimationFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame;
const cancelAnimationFrame =
window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame;
const scrollNode = noticeContentEl.current;
const distance = scrollNode.clientWidth / 2;
scrollNode.style.left = scrollNode.style.left || 0;
window.__offset = window.__offset || 0;
let requestId = null;
const scrollLeft = () => {
const speed = 0.5;
window.__offset = window.__offset + speed;
scrollNode.style.left = -window.__offset + "px";
// 关键行:当距离小于偏移量时,重置偏移量
if (distance <= window.__offset) window.__offset = 0;
requestId = requestAnimationFrame(scrollLeft);
};
requestId = requestAnimationFrame(scrollLeft);
if (pause) cancelAnimationFrame(requestId);
return () => cancelAnimationFrame(requestId);
}, [notice, pause]);
版权声明 : 本文未使用任何知识共享协议授权,您可以任何形式自由转载或使用。

发表评论 / 取消回复