Posts: 打字机效果的 Hitokoto(html+css+js)
打字机效果的 Hitokoto(html+css+js)
效果
讲
文本将写在<span class="text" id="hitokoto_text">:D 获取中...</span>
里
JavaScript 中
1 2 3
| const typingSpeed = 180; const deletingSpeed = 100; const delayBetweenCycles = 2500;
|
完整源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>打字机效果的 Hitokoto</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: rgb(43, 52, 82); } .text { font-family: 'fangsong'; display: inline-block; position: relative; font-size: 40px; height: 60px; line-height: 60px; color: rgb(245, 245, 245); } .text::after { content: ''; position: absolute; right: -10px; top: 5px; height: 50px; width: 3px; background-color: #fff; animation: blink 0.5s steps(1) infinite; } @keyframes blink { 0%, 100% { background-color: #fff; } 50% { background-color: transparent; } } </style> </head> <body> <h1> <span class="text" id="hitokoto_text">:D 获取中...</span> </h1> <script> const textElement = document.querySelector('.text'); let charIndex = 0; let isDeleting = false; let hitokotoText = ''; let typingInterval; const typingSpeed = 180; const deletingSpeed = 100; const delayBetweenCycles = 2500;
function typeWriter() { if (isDeleting) { textElement.innerHTML = hitokotoText.slice(0, charIndex--); } else { textElement.innerHTML = hitokotoText.slice(0, ++charIndex); } if (!isDeleting && charIndex === hitokotoText.length) { setTimeout(() => isDeleting = true, delayBetweenCycles); } else if (isDeleting && charIndex === 0) { isDeleting = false; clearInterval(typingInterval); fetchHitokoto(); return; } const speed = isDeleting ? deletingSpeed : typingSpeed; typingInterval = setTimeout(typeWriter, speed); }
function fetchHitokoto() { fetch('https://v1.hitokoto.cn').then(response => response.json()).then(data => { hitokotoText = data.hitokoto; charIndex = 0; typeWriter(); }).catch(console.error); } fetchHitokoto(); </script> </body> </html>
|
参考资料
- 打字机效果 html+css+js
- 语句接口 - 一言