用React实现上下跑马灯

基本思想:

  1. 利用transform:translateY()实现上下滑动,transition控制滑动时间,
  2. 把原数组拼接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 (
    
{ content.concat(content[0]).map((itm, i) => (
{itm}
)) }
); }
// 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前端)