阅读目录
最终效果
- 最终效果
- index.html
- index.js
- index.css
DOCTYPE html>
自动打字效果的实现
开始打字
设置速度:
index.js
const textEl = document.getElementById('text')
const speedEl = document.getElementById('speed')
const text =
'毛泽东的名作《沁园春·雪》,北国风光,千里冰封,万里雪飘。望长城内外,惟余莽莽;大河上下,顿失滔滔。山舞银蛇,原驰蜡象,欲与天公试比高。须晴日,看红装素裹,分外妖娆。江山如此多娇,引无数英雄竞折腰。惜秦皇汉武,略输文采;唐宗宋祖,稍逊风骚。一代天骄,成吉思汗,只识弯弓射大雕。俱往矣,数风流人物,还看今朝。'
let idx = 1
let speed = 100 / 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 = 100 / e.target.value)
index.css
* {
box-sizing: border-box;
}
body {
background-color:#00a6bc;
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
overflow: hidden;
margin: 0;
}
h1{margin-left:50px;margin-right:50px;
}
#text{
color:#fff;
}
div {
position: absolute;
bottom: 20px;
font-size: 18px;
background-color: #fff;
opacity:0.8;
}
input {
width: 50px;
padding: 5px;
font-size: 18px;
background-color: #fafafa;
border: none;
text-align: center;
}
input:focus {
outline: none;
}