原生JS实现跑马灯marquee

一、实现效果

二、源码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>跑马灯</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body {
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .wrapper {
      width: 60%;
      height: 30px;
      background-color: #000;
      overflow: hidden;
      position: relative;
    }

    .text {
      color: #fff;
      white-space: nowrap;
      line-height: 30px;
      position: absolute;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="text">海外徒闻更九州,他生未卜此生休。 空闻虎旅传宵柝,无复鸡人报晓筹。 此日六军同驻马,当时七夕笑牵牛。 如何四纪为天子,不及卢家有莫愁。</div>
  </div>

  <script>
    const wrapper = document.getElementsByClassName("wrapper")[0]  // 容器
    const text = document.getElementsByClassName("text")[0]  // 文本

    const wrapperWidth = wrapper.clientWidth  // 容器的总宽度
    const textWidth = text.clientWidth  // 文本的总宽度
    let textRun = null // 循环器
    text.style.left = wrapperWidth + "px"  // 开始滚动前设定文本在容器最右侧以外

    textRoll()

    // 开始滚动
    function textRoll() {
      let textLeft = text.style.left.split("px")[0]  // 获取文本的left值
      textRun = setInterval(() => {  // 设定循环器,通过left滚动文本
        textLeft -= 1
        text.style.left = textLeft + "px"
        if (textLeft == -textWidth) {  // 当到达文本最大宽度(播放完文本)
          clearInterval(textRun)
          setTimeout(() => {  // 间隔1.5s后再次执行文本滚动
            text.style.left = wrapperWidth + "px"
            textRoll()
          }, 1500);
        }
      }, 10);
    }

    // 鼠标 移入/移出 时 停止/开始 滚动
    wrapper.onmouseover = function() {
      clearInterval(textRun)
    }
    wrapper.onmouseout = function() {
      textRoll()
    }
  </script>
</body>
</html>

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值