温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

基于React.js如何实现简单的文字跑马灯效果

发布时间:2023-01-16 09:31:28 来源:亿速云 阅读:125 作者:iii 栏目:开发技术

这篇文章主要介绍“基于React.js如何实现简单的文字跑马灯效果”,在日常操作中,相信很多人在基于React.js如何实现简单的文字跑马灯效果问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”基于React.js如何实现简单的文字跑马灯效果”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

我想到的最简单的方法,就是定位啦,定时移动这个文字块不就跑起来了。

需要注意的是,要判断文字的宽度,当文字超出屏幕的宽度的时候再动起来,我用的是hook的写法,要在销毁页面的时候清掉定时器。定时器要放在useRef里面。

const timer = useRef<any>(null);
const [left, setLeft] = useState(0);
const contentRef = useRef<any>(null);
useEffect(() => {
    // 当监听到文字变化时,一定要先清掉定时器,如果文字较短的话就不会再启动    
    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是负数,Ï当数字移动到最后的时候,下一次从父元素的宽度开始,看起来就是一直在向左移动
         // 文字框的宽度要时时获取
         // setLeft要从回调里面获取,不然不能时时更新          
         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没法获取自适应宽度,咋判断文字移动到末尾了?但是我觉得,css肯定是可以办到,于是我继续探索...

animation走起,,,咱们假设外边框长120px,文字长240px

@keyframes run {  
0% {    transform: translateX(0);  }  
50% {    transform: translateX(-240px);  }  
50% {    transform: translateX(120px);  }  
100% {    transform: translateX(-240px);  }
}

总感觉有啥不对,这个字咋往回跑,这感觉跑来跑去的。。。

基于React.js如何实现简单的文字跑马灯效果

平心静气~没事没事,不就是个小bug么~

仔细思考一下,这只要写两个动画就解决了,因为其实除了第一次不同,后面都是从右边进入视角的有木有。

@keyframes run {   
from {    transform: translateX(0);  }  
to {    transform: translateX(-240px);  }
}
@keyframes loop {  
from {    transform: translateX(120px);  }  
to {    transform: translateX(-240px);  }
}

咱们用的时候,第一个走一遍就好了,循环后面那个:

.textContent {    
white-space: nowrap;    
animation-name: run, loop;    
animation-duration: 5s;    
animation-iteration-count: 1, infinite;
animation-timing-function: linear;    
position: relative;  
}

look,是不是好多了~

基于React.js如何实现简单的文字跑马灯效果

接下来就是文字长度的问题了~咋们咋控制他要不要动啊?还有移动的时间和距离咋控制??

首先动画时间,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,
             // 第二个动画等第一个执行之后执行
             animationDelay: duration? `0s, ${duration}` :'',              
        }}      
   >       
  {props.children}      
  </div>    
</div>  );

完整的样式

// 设置父元素的宽度
@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%);  }
}

这个父元素的宽度是不是写死了,要是要使用的话只能手动改@width,咱有木有办法通过js传过来?你知道怎么改更好么?

哈哈,咱们基本上已经完成了这种简单的从左向右移动的文字跑马灯(为自己鼓掌),接下来就是升级版的了,跑马灯plus。实现一个向上滚动的跑马灯。

咱们在第一步的基础上来做一个向上滚动的跑马灯plus。

我们加一个向上的按钮,可以控制文字跑动的方向,当然向右向下同理~这里就不做了

 <>      
<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(() => {    
  // 当监听到文字变化时,一定要先清掉定时器,如果文字较短的话就不会再启动    
  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]);

看一下成果:

基于React.js如何实现简单的文字跑马灯效果

这种单行滚动的效果,能不能实现一下?就是滚动一行停留一段时间再继续滚动

基于React.js如何实现简单的文字跑马灯效果

这个也比较简单,我用我上面的方法在引申一下,你们也可以用其他方法,animatioin也可以。

我在定时器里面在加一个延时timeout

timer.current = setInterval(() => {            
   setTop(state => {
     // 当行数是40的整倍数的时候延迟执行移动              
     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如何实现简单的文字跑马灯效果

到此,关于“基于React.js如何实现简单的文字跑马灯效果”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI