先准备一个html的模版:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<style>
body {
background-color: black;
color: white;
}
#switch-box {
color: #0cc4fb;
}
</style>
</head>
<body>
我要成为
<span id="switch-box"></span>
高手
</body>
</html>
在switch-box中实现打字效果,得利用js,首先定义一个字符串数组,用于在打字机中切换文字,然后定义一个函数将数组中的字放到内容中,每次切换后索引+1,然后循环调用这个函数,当索引大于数组长度的时候,把索引重新归0
const stringarray = ['c++','go','java','js','php']
let switch_box = document.getelementbyid('switch-box')
// 定义数组索引
let index = 0
let delay = 500
let changetext = () => {
switch_box.textcontent = stringarray[index]
index ++
if(index >= stringarray.length){
index = 0
}
settimeout(changetext,delay)
}
changetext()
这其实已经能实现切换了,只是没有打字效果,我们再利用js,用于显示一个个字符的显示,利用substring切割字符,每次字符数量+1,当切割全部的时候,就该执行删除了,所以应该定义一个删除的标志,在删除完之后,就应该切换到下一个字符了。
下面是完整代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<style>
body {
background-color: black;
color: white;
}
#switch-box {
color: #0cc4fb;
}
</style>
</head>
<body>
我要成为
<span id="switch-box"></span>
高手
<script>
const stringarray = ['c++','go','java','js','php']
let switch_box = document.getelementbyid('switch-box')
// 定义数组索引
let index = 0
let delay = 0
let charindex = 0
// 删除标志
let isdelete = false
let defaultdelay = 300
let waitdalay = 1000
let changetext = () => {
switch_box.textcontent = stringarray[index].substring(0,charindex);
if(!isdelete){
delay = defaultdelay
charindex ++
if(charindex > stringarray[index].length){
// 当charindex已经大于字符的长度的时候,表示应该执行删除动画了
isdelete = true
delay = waitdalay
}
}else{
delay = defaultdelay
charindex --
if(charindex < 1){
isdelete = false
index ++
if(index >= stringarray.length){
index = 0
}
}
}
settimeout(changetext,delay)
}
changetext()
</script>
</body>
</html>
最后补充下文字后的光标闪烁效果
/*打字样式光标*/
#switch-box::after {
content: "i";
font-size: 18px;
display: inline-block;
vertical-align: top;
font-weight: lighter;
animation: flicker .5s infinite;
}
/*光标闪烁动画*/
@keyframes flicker {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
效果图

到此这篇关于基于javascript实现惊艳的打字机效果的文章就介绍到这了,更多相关javascript打字机内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论