基于React.js實現(xiàn)簡單的文字跑馬燈效果
剛好手上有一個要實現(xiàn)文字跑馬燈的react項目,然后ant-design上面沒有這個組件,于是只能自己手擼一個。
我想到的最簡單的方法,就是定位啦,定時移動這個文字塊不就跑起來了。
需要注意的是,要判斷文字的寬度,當(dāng)文字超出屏幕的寬度的時候再動起來,我用的是hook的寫法,要在銷毀頁面的時候清掉定時器。定時器要放在useRef里面。
const timer = useRef<any>(null);
const [left, setLeft] = useState(0);
const contentRef = useRef<any>(null);
useEffect(() => {
// 當(dāng)監(jiān)聽到文字變化時,一定要先清掉定時器,如果文字較短的話就不會再啟動
if (timer.current) { clearInterval(timer.current); }
const contentDom = contentRef.current;
if (contentDom) {
const obj = contentDom.getBoundingClientRect();
// 判斷文字框長度
if (obj.width > props.width) {
timer.current = setInterval(() => {
// 注意state是負數(shù),?當(dāng)數(shù)字移動到最后的時候,下一次從父元素的寬度開始,看起來就是一直在向左移動
// 文字框的寬度要時時獲取
// setLeft要從回調(diào)里面獲取,不然不能時時更新
setLeft((state) =>-state >= contentDom.getBoundingClientRect().width ? props.width : state - 1, ); }, 100);
} else { setLeft(0); }
}
}, [props.children]);
useEffect(() => {
// 注銷時,清空定時器
return () => {
if (timer.current) { clearInterval(timer.current); }
};
}, []);
return (<div className={styles.noticeCompWrapper} style={{ width: props.width, ...props.style }}>
<div ref={contentRef} className={styles.noticeContent} style={{ left }}> {props.children} </div>
</div> );
.noticeCompWrapper {
height: 40px;
line-height: 40px;
overflow: hidden;
position: relative;
.noticeContent {
white-space: nowrap;
position: absolute;
}
}這移動效果還可以吧,時間間隔一定要小,不然就會一卡一卡的

第一種很容易吧,其實最開始是想用純css來寫的,考慮到css沒法獲取自適應(yīng)寬度,咋判斷文字移動到末尾了?但是我覺得,css肯定是可以辦到,于是我繼續(xù)探索...
animation走起,,,咱們假設(shè)外邊框長120px,文字長240px
@keyframes run {
0% { transform: translateX(0); }
50% { transform: translateX(-240px); }
50% { transform: translateX(120px); }
100% { transform: translateX(-240px); }
}總感覺有啥不對,這個字咋往回跑,這感覺跑來跑去的。。。

平心靜氣~沒事沒事,不就是個小bug么~
仔細思考一下,這只要寫兩個動畫就解決了,因為其實除了第一次不同,后面都是從右邊進入視角的有木有。
@keyframes run {
from { transform: translateX(0); }
to { transform: translateX(-240px); }
}
@keyframes loop {
from { transform: translateX(120px); }
to { transform: translateX(-240px); }
}咱們用的時候,第一個走一遍就好了,循環(huán)后面那個:
.textContent {
white-space: nowrap;
animation-name: run, loop;
animation-duration: 5s;
animation-iteration-count: 1, infinite;
animation-timing-function: linear;
position: relative;
}look,是不是好多了~

接下來就是文字長度的問題了~咋們咋控制他要不要動???還有移動的時間和距離咋控制??
首先動畫時間,less肯定是算不出來了,那我們就在js外面計算一下哈~方法和上面類似,要取元素的寬度。
const contentRef = useRef<any>(null);
const [duration, setDuration] = useState('');
useEffect(() => {
const dom = contentRef.current;
if (dom) {
const { width } = dom.getBoundingClientRect();
if (width > props.width) {
// 我這邊取的速度是按一個字的大小
setDuration(width / 16 + 's');
} else {
// 小于寬度的時候清掉時間
setDuration('');
}
} else { setDuration(''); }
}, [props.children]);
return (<div style={{ width: props.width, ...props.style }} className={styles.wrapper} >
<div
className={styles.textContent}
ref={contentRef}
// 計算好動畫時間傳過去
style={{
animationDuration: duration,
// 第二個動畫等第一個執(zhí)行之后執(zhí)行
animationDelay: duration? `0s, ${duration}` :'',
}}
>
{props.children}
</div>
</div> );完整的樣式
// 設(shè)置父元素的寬度
@width: 120px;
.wrapper {
position: relative;
overflow: hidden;
width: @width;
height: 40px;
line-height: 40px;
.textContent {
white-space: nowrap;
animation-name: run, roop;
animation-iteration-count: 1, infinite;
animation-timing-function: linear;
// 這個很重要,不然寬度就和父元素一樣
position: absolute;
}
}
@keyframes run {
from { transform: translateX(0); }
to {
// 這個100% 是文字的
transform: translateX(-100%);
}
}
@keyframes roop {
from { transform: translateX(@width); }
to { transform: translateX(-100%); }
}不錯不錯,這樣就解決了時間和制動的問題了~
不過...,這還不夠完美。NOT PERFACT!
這個父元素的寬度是不是寫死了,要是要使用的話只能手動改@width,咱有木有辦法通過js傳過來?你知道怎么改更好么?
哈哈,咱們基本上已經(jīng)完成了這種簡單的從左向右移動的文字跑馬燈(為自己鼓掌),接下來就是升級版的了,跑馬燈plus。實現(xiàn)一個向上滾動的跑馬燈。
咱們在第一步的基礎(chǔ)上來做一個向上滾動的跑馬燈plus。
我們加一個向上的按鈕,可以控制文字跑動的方向,當(dāng)然向右向下同理~這里就不做了
<>
<div
className={styles.noticeCompWrapper}
style={{ width: props.width, ...props.style, marginBottom: 10 }}
>
<div
ref={contentRef}
className={styles.noticeContent}
style={{ left, top,
// 換行的邏輯一定要加上,上下移動的需要換行
whiteSpace: direction == DirectionEnum.左 ? 'nowrap' : 'initial',
}}
>
{props.children}
</div>
</div>
<Space>
<Button onClick={() => { setDirection(DirectionEnum.左); setTop(0); }}> 向左</Button>
<Button onClick={() => { setDirection(DirectionEnum.上); setLeft(0); }}> 向上</Button>
</Space>
</>判斷下移動方向
useEffect(() => {
// 當(dāng)監(jiān)聽到文字變化時,一定要先清掉定時器,如果文字較短的話就不會再啟動
if (timer.current) { clearInterval(timer.current); }
const contentDom = contentRef.current;
if (contentDom) {
const obj = contentDom.getBoundingClientRect();
if (direction == DirectionEnum.左) {
// 同上...
} else if (direction == DirectionEnum.上) {
// 向上
if (obj.height > 40) {
timer.current = setInterval(() => {
setTop(state =>-state >= contentDom.getBoundingClientRect().height ? 40 : state - 1);
}, 30);
}
} else {
setLeft(0);
setTop(0);
}
}
}, [props.children, direction]);
看一下成果:

這種單行滾動的效果,能不能實現(xiàn)一下?就是滾動一行停留一段時間再繼續(xù)滾動

這個也比較簡單,我用我上面的方法在引申一下,你們也可以用其他方法,animatioin也可以。
我在定時器里面在加一個延時timeout
timer.current = setInterval(() => {
setTop(state => {
// 當(dāng)行數(shù)是40的整倍數(shù)的時候延遲執(zhí)行移動
if ((state - 1) % 40 == 0) {
setTimeout(() => {
setTop(state1 => -state1 >= contentDom.getBoundingClientRect().height ? 40 : state1 - 1);
}, 500);
return state;
} else {
return -state >= contentDom.getBoundingClientRect().height? 40 : state - 1;
}
});
}, 30);效果:

以上就是基于React.js實現(xiàn)簡單的文字跑馬燈效果的詳細內(nèi)容,更多關(guān)于React文字跑馬燈的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
react?umi?刷新或關(guān)閉瀏覽器時清除localStorage方式
這篇文章主要介紹了react?umi?刷新或關(guān)閉瀏覽器時清除localStorage方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
React中memo useCallback useMemo方法作用及使用場景
這篇文章主要為大家介紹了React中三個hooks方法memo useCallback useMemo的作用及使用場景示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助2023-03-03
詳解如何用webpack4從零開始構(gòu)建react開發(fā)環(huán)境
這篇文章主要介紹了詳解如何用webpack4從零開始構(gòu)建react開發(fā)環(huán)境,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
react-router-dom 嵌套路由的實現(xiàn)
這篇文章主要介紹了react-router-dom 嵌套路由的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
react實現(xiàn)數(shù)據(jù)監(jiān)聽方式
這篇文章主要介紹了react實現(xiàn)數(shù)據(jù)監(jiān)聽方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08

