代码描述:JavaScript字符串 动画轮播效果。JavaScript字符串动画轮播效果
分享一段代码实例,它利用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>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能