实现炫酷的打字机效果,需求:
打开网站光标闪烁,逐字出现,显示完整后光标消失
1、template中的代码
<div id="slogan"></div>
<div class="cursors" id="cursors"></div>
2、script中的代码
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
onMounted(() => {
getSlogan()
})
//光标动画
let time = null
const getSlogan = () => {
let index = 0;
const typingContainer = document.getElementById('slogan');
const cursorElement = document.getElementById('cursors');
const text = 'AI数字员工,赋能智慧政务新未来'
function typeLetter () {
cursorElement.style.display = 'block'; // 开始显示光标
if (index < text.length) {
typingContainer.innerHTML += text.charAt(index);
index++;
time = setTimeout(typeLetter, 110); // 调整打字速度
} else {
cursorElement.style.display = 'none'; // 文字结束后隐藏光标
clearTimeout(time)
time = null
}
}
typeLetter();
}
onBeforeUnmount(() => {
clearTimeout(time)
})
3、
#slogan {
font-weight: 400;
font-size: 36px;
display: inline-block;
// font-family: Arial, sans-serif;
margin: 50px 0 20px;
}
.cursors {
height: 36px;
margin: 34px 0 0 2px;
/* 初始不显示光标 */
display: none;
width: 10px;
background-color: #fff;
/* 光标 */
animation: blink steps(40) 1s step-start infinite;
}
@keyframes blink {
50% {
background-color: transparent;
}
}