共计 1416 个字符,预计需要花费 4 分钟才能阅读完成。
根本思维:
- 利用 transform:translateY() 实现高低滑动,transition 管制滑动工夫,
- 把原数组拼接 0 下标的数据用于展现,当滑动到最初一个,马上定位到第一个。(最初一个与第一个雷同)
代码示例:
// index.jsx
import React, {useRef, useState} from 'react';
import {useInterval} from 'ahooks';
import './style.scss';
function Marquee() {const marqueeRef = useRef(null);
const content = [
'鸣谢生命有你参加,哂纳我的邀请',
'青春太平盛世,咱们潦草地离散',
'我对你付出的青春 这么多年',
'我的心事,蒸发成云,再下场雨却舍不得淋湿你',
];
useInterval(() => {if (!marqueeRef || !marqueeRef.current) return;
const {height} = marqueeRef.current.getBoundingClientRect();
const translateYItem = Math.floor(height / (content.length + 1));
const nextIndex = index + 1;
marqueeRef.current.style.transform = `translateY(-${translateYItem * nextIndex}px)`;
marqueeRef.current.style.transition = 'transform 1s';
if (index >= content.length - 1) {
// 最初一个
setTimeout(() => {setIndex(0);
marqueeRef.current.style.transform = 'translateY(0px)';
marqueeRef.current.style.transition = 'transform 0s';
}, 1000);
} else {setIndex(nextIndex);
}
}, 2000);
return (
<div className="marquee-container">
<div className="marquee-wrapper">
<div className="marquee-content" ref={marqueeRef}>
{content.concat(content[0]).map((itm, i) => (<div key={`${itm}-${i}`} className="marquee-content-itm">
{itm}
</div>
))
}
</div>
</div>
</div>
);
}
// style.scss
.marquee-container {
width: 100%;
.marquee-wrapper {
height: 17px;
overflow: hidden;
.marquee-content {transform: translateY(0);
transition: transform 1s;
display: flex;
flex-direction: column;
align-items: flex-start;
.marquee-content-itm {
line-height: 17px;
font-size: 12px;
color: #5e1400;
}
}
}
}
正文完
发表至: javascript
2021-02-08