📢前言
代码取自开源项目50projects50days,用作个人学习和巩固三件套的知识,增加了注释,可能会有小改动。
在线演示地址
📝实现思路及效果

💻代码
index.html
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
| <!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"> <link rel="stylesheet" href="style.css"> <title>标题打字输入</title> <link rel="shortcut icon" href="../logo.svg"> </head>
<body> <h1 id="text"></h1> <div> <label for="speed">Speed:</label> <input type="number" name="speed" id="speed" value="1" min="1" max="10" step="1"> </div>
<script src="script.js"></script> </body>
</html>
|
style.css
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
| @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
* { box-sizing: border-box; }
body { background-color: darksalmon; font-family: 'Roboto', sans-serif; display: flex; font-display: column; align-items: center; justify-content: center; height: 100vh; overflow: hidden; margin: 0; }
div { position: absolute; bottom: 20px; background-color: rgba(0, 0, 0, 0.1); padding: 10px 20px; font-size: 18x; }
input { width: 50px; font-size: 18px; padding: 5px; text-align: center; background-color: darksalmon; border: 0; }
input:focus { outline: none; }
|
script.js
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
| const textEl = document.getElementById("text"); const speedEl = document.getElementById("speed"); const text = "原来你也玩原神!"; let idx = 1;
let speed = 300 / speedEl.value;
writeText();
function writeText() { textEl.innerText = text.slice(0, idx);
idx++;
if (idx > text.length) { idx = 1; }
setTimeout(writeText, speed); }
speedEl.addEventListener("input", (e) => { speed = 300 / e.target.value; });
|