聊聊怎么实现h5页面title滚动显示

1,034 阅读1分钟

需求

  • 页面 title 滚动显示
  • 每滚动完一轮,暂停 2s

实现思路

从第二个字符开始截取 title 字符串,拼接上 title 的第一个字符,作为新的页面 title. 设置一个定时器,定时更新页面 title。通过调节 setTimeout 的延时参数,可按需调整滚动速度。

代码实现

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <title ref="">这是一个滚动标题</title>
    <script language=javascript >
      let text = document.title + ' '
      let timerId
      let times = 0
      function newtext() {
          times++
          clearTimeout(timerId)
          document.title = text.substring(1,text.length) + text.substring(0,1)
          text = document.title.substring(0,text.length)

          let delay = 500
          if (times === text.length) {
            delay = 2000
            times = 0
            text = document.title + ' '
          }
          timerId = setTimeout("newtext()", delay)
      }
     newtext();
    </script>
  </head>
  <body>
  </body>
</html>

注意

页面加载的时候立即执行上述定义的方法newtext(); 拿到页面 title 后可以加上一个空格字符,再做字符串截取,方便区分 title 一次滚动完成。

本文使用 mdnice 排版