分享一段代码实例,它利用js实现了字符串动画轮播效果。

代码实例如下:
   [ 其他 ] 运行代码    下载代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51qianduan.com/" />
<title>51前端</title>
<style>
html, body {
  background: #212121;
  height: 100%;
}
.container {
  height: 100%;
  width: 100%;
  justify-content: center;
  align-items: center;
  display: flex;
}
.text {
  font-weight: 100;
  font-size: 50px;
  color: #FAFAFA;
}
.dud {
  color: #757575;
}
</style>
<script>
class TextScramble {
  constructor(el) {
    this.el = el;
    this.chars = '!<>-_\\\\/[]{}—=+*^?#________';
    this.update = this.update.bind(this);
  }
  setText(newText) {
    const oldText = this.el.innerText;
    const length = Math.max(oldText.length, newText.length);
    const promise = new Promise((resolve) => this.resolve = resolve);
    this.queue = [];
    for (let index = 0; index < length; index++) {
      const from = oldText[index] || '';
      const to = newText[index] || '';
      const start = Math.floor(Math.random() * 40);
      const end = start + Math.floor(Math.random() * 40);
      this.queue.push({ from, to, start, end });
    }
    cancelAnimationFrame(this.frameRequest);
    this.frame = 0;
    this.update();
    return promise;
  }
  update() {
    let output = '';
    let complete = 0;
    for (let index = 0, n = this.queue.length; index < n; index++) {
      let { from, to, start, end, char } = this.queue[index];
      if (this.frame >= end) {
        complete++;
        output += to;
      } else if (this.frame >= start) {
        if (!char || Math.random() < 0.28) {
          char = this.randomChar();
          this.queue[index].char = char;
        }
        output += `<span class="dud">${char}</span>`;
      } else {
        output += from;
      }
    }
    this.el.innerHTML = output;
    if (complete === this.queue.length) {
      this.resolve();
    } else {
      this.frameRequest = requestAnimationFrame(this.update);
      this.frame++;
    }
  }
  randomChar() {
    return this.chars[Math.floor(Math.random() * this.chars.length)];
  }
}
  
window.onload=function(){
  const phrases = [
    '51前端',
    'css教程',
    'js教程',
    'softwhy.com',
    '努力奋斗',
    'json教程'
  ];
  
  const el = document.querySelector('.text');
  const fx = new TextScramble(el);
  
  let counter = 0;
  const next = () => {
    fx.setText(phrases[counter]).then(() => {
      setTimeout(next, 800)
    })
    counter = (counter + 1) % phrases.length;
  }
  next()
}
</script>
</head>
<body>
<div class="container">
  <div class="text"></div>
</div>
</body>
</html>

代码描述:JavaScript字符串 动画轮播效果。JavaScript字符串动画轮播效果



169 226



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册



×
×
51前端

注册

×
绑定手机

请绑定手机号,在继续操作

×
单次下载支付

应付金额:279

支付完成后,回到下载页面,在进行下载

官方QQ群
意见反馈
qq群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到