经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » React » 查看文章
基于React.js实现简单的文字跑马灯效果
来源:jb51  时间:2023/1/16 9:16:15  对本文有异议

刚好手上有一个要实现文字跑马灯的react项目,然后ant-design上面没有这个组件,于是只能自己手撸一个。

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

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

  1. const timer = useRef<any>(null);
  2. const [left, setLeft] = useState(0);
  3. const contentRef = useRef<any>(null);
  4. useEffect(() => {
  5. // 当监听到文字变化时,一定要先清掉定时器,如果文字较短的话就不会再启动
  6. if (timer.current) { clearInterval(timer.current); }
  7. const contentDom = contentRef.current;
  8. if (contentDom) {
  9. const obj = contentDom.getBoundingClientRect();
  10. // 判断文字框长度
  11. if (obj.width > props.width) {
  12. timer.current = setInterval(() => {
  13. // 注意state是负数,?当数字移动到最后的时候,下一次从父元素的宽度开始,看起来就是一直在向左移动
  14. // 文字框的宽度要时时获取
  15. // setLeft要从回调里面获取,不然不能时时更新
  16. setLeft((state) =>-state >= contentDom.getBoundingClientRect().width ? props.width : state - 1, ); }, 100);
  17. } else { setLeft(0); }
  18. }
  19. }, [props.children]);
  20. useEffect(() => {
  21. // 注销时,清空定时器
  22. return () => {
  23. if (timer.current) { clearInterval(timer.current); }
  24. };
  25. }, []);
  26. return (<div className={styles.noticeCompWrapper} style={{ width: props.width, ...props.style }}>
  27. <div ref={contentRef} className={styles.noticeContent} style={{ left }}> {props.children} </div>
  28. </div> );
  29.  
  30. .noticeCompWrapper {
  31. height: 40px;
  32. line-height: 40px;
  33. overflow: hidden;
  34. position: relative;
  35. .noticeContent {
  36. white-space: nowrap;
  37. position: absolute;
  38. }
  39. }

这移动效果还可以吧,时间间隔一定要小,不然就会一卡一卡的

第一种很容易吧,其实最开始是想用纯css来写的,考虑到css没法获取自适应宽度,咋判断文字移动到末尾了?但是我觉得,css肯定是可以办到,于是我继续探索...

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

  1. @keyframes run {
  2. 0% { transform: translateX(0); }
  3. 50% { transform: translateX(-240px); }
  4. 50% { transform: translateX(120px); }
  5. 100% { transform: translateX(-240px); }
  6. }

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

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

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

  1. @keyframes run {
  2. from { transform: translateX(0); }
  3. to { transform: translateX(-240px); }
  4. }
  5. @keyframes loop {
  6. from { transform: translateX(120px); }
  7. to { transform: translateX(-240px); }
  8. }

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

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

look,是不是好多了~

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

首先动画时间,less肯定是算不出来了,那我们就在js外面计算一下哈~方法和上面类似,要取元素的宽度。

  1. const contentRef = useRef<any>(null);
  2. const [duration, setDuration] = useState('');
  3. useEffect(() => {
  4. const dom = contentRef.current;
  5. if (dom) {
  6. const { width } = dom.getBoundingClientRect();
  7. if (width > props.width) {
  8. // 我这边取的速度是按一个字的大小
  9. setDuration(width / 16 + 's');
  10. } else {
  11. // 小于宽度的时候清掉时间
  12. setDuration('');
  13. }
  14. } else { setDuration(''); }
  15. }, [props.children]);
  16. return (<div style={{ width: props.width, ...props.style }} className={styles.wrapper} >
  17. <div
  18. className={styles.textContent}
  19. ref={contentRef}
  20. // 计算好动画时间传过去
  21. style={{
  22. animationDuration: duration,
  23. // 第二个动画等第一个执行之后执行
  24. animationDelay: duration? `0s, ${duration}` :'',
  25. }}
  26. >
  27. {props.children}
  28. </div>
  29. </div> );

完整的样式

  1. // 设置父元素的宽度
  2. @width: 120px;
  3. .wrapper {
  4. position: relative;
  5. overflow: hidden;
  6. width: @width;
  7. height: 40px;
  8. line-height: 40px;
  9. .textContent {
  10. white-space: nowrap;
  11. animation-name: run, roop;
  12. animation-iteration-count: 1, infinite;
  13. animation-timing-function: linear;
  14. // 这个很重要,不然宽度就和父元素一样
  15. position: absolute;
  16. }
  17. }
  18. @keyframes run {
  19. from { transform: translateX(0); }
  20. to {
  21. // 这个100% 是文字的
  22. transform: translateX(-100%);
  23. }
  24. }
  25. @keyframes roop {
  26. from { transform: translateX(@width); }
  27. to { transform: translateX(-100%); }
  28. }

不错不错,这样就解决了时间和制动的问题了~

不过...,这还不够完美。NOT PERFACT!

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

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

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

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

  1. <>
  2. <div
  3. className={styles.noticeCompWrapper}
  4. style={{ width: props.width, ...props.style, marginBottom: 10 }}
  5. >
  6. <div
  7. ref={contentRef}
  8. className={styles.noticeContent}
  9. style={{ left, top,
  10. // 换行的逻辑一定要加上,上下移动的需要换行
  11. whiteSpace: direction == DirectionEnum.左 ? 'nowrap' : 'initial',
  12. }}
  13. >
  14. {props.children}
  15. </div>
  16. </div>
  17. <Space>
  18. <Button onClick={() => { setDirection(DirectionEnum.左); setTop(0); }}> 向左</Button>
  19. <Button onClick={() => { setDirection(DirectionEnum.上); setLeft(0); }}> 向上</Button>
  20. </Space>
  21. </>

判断下移动方向

  1. useEffect(() => {
  2. // 当监听到文字变化时,一定要先清掉定时器,如果文字较短的话就不会再启动
  3. if (timer.current) { clearInterval(timer.current); }
  4. const contentDom = contentRef.current;
  5. if (contentDom) {
  6. const obj = contentDom.getBoundingClientRect();
  7. if (direction == DirectionEnum.左) {
  8. // 同上...
  9. } else if (direction == DirectionEnum.上) {
  10. // 向上
  11. if (obj.height > 40) {
  12. timer.current = setInterval(() => {
  13. setTop(state =>-state >= contentDom.getBoundingClientRect().height ? 40 : state - 1);
  14. }, 30);
  15. }
  16. } else {
  17. setLeft(0);
  18. setTop(0);
  19. }
  20. }
  21. }, [props.children, direction]);

看一下成果:

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

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

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

  1. timer.current = setInterval(() => {
  2. setTop(state => {
  3. // 当行数是40的整倍数的时候延迟执行移动
  4. if ((state - 1) % 40 == 0) {
  5. setTimeout(() => {
  6. setTop(state1 => -state1 >= contentDom.getBoundingClientRect().height ? 40 : state1 - 1);
  7. }, 500);
  8. return state;
  9. } else {
  10. return -state >= contentDom.getBoundingClientRect().height? 40 : state - 1;
  11. }
  12. });
  13. }, 30);

效果:

以上就是基于React.js实现简单的文字跑马灯效果的详细内容,更多关于React文字跑马灯的资料请关注w3xue其它相关文章!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号