用JS和CSS3实现打字动画
2021-04-26 23:29
阅读:321
YPE html>
我们经常希望一段文本中的字符逐个显示,模拟出一种打字的效果。类似于终端命令行的感觉。最终效果
用JS去实现:
html:
js代码:
const $ = attr => document.querySelector(attr);
const textDom = $(‘.text‘);
const cursorDom = $(‘.cursor‘);
const input = (text) => {
const textArr = text.split(‘‘);
let index = 0;
const timer = setInterval(() => {
const showText = textArr.slice(0, index).join(‘‘);
textDom.innerHTML = showText;
index++;
if (index > textArr.length) clearInterval(timer);
}, 100);
setInterval(() => {
if (cursorDom.style.display === ‘none‘) {
cursorDom.style.display = ‘inline‘;
} else {
cursorDom.style.display = ‘none‘;
}
}, 500);
}
input(‘The ZGMF-X20A Strike Freedom Gundam (aka Strike Freedom, Freedom) is the successor of the ZGMF-X10A Freedom.‘);
用CSS3去实现:
JS实现给人的感觉又臭又长,那能不能用CSS去实现呢?
html:
The ZGMF-X20A Strike Freedom Gundam (aka Strike Freedom, Freedom) is the successor of the ZGMF-X10A Freedom.
@keyframes typing {
from { width: 0 }
}
@keyframes caret {
50% { border-right-color: transparent; }
}
h1 {
font: bold 200% Consolas, Monaco, monospace;
width: 108ch;
white-space: nowrap;
overflow: hidden;
border-right: .05em solid;
animation: typing 10.8s steps(108),
caret 1s steps(1) infinite;
}
字符串长度是108;
总结:
js实现不用考虑兼容性,CSS3实现的需要考虑兼容性,还要兼顾字符串的长度and宽度且不能换行==,不能换行,不过使用起来似乎更简单一些,具体的取舍还是看个人习惯。
补充:
以前看某公司的主页有这个打字动画的效果,今天看发现有个代码高亮的效果,于是优化了代码:
//...
const timer = setInterval(() => {
const showText = textArr.slice(0, index).join(‘‘);
textDom.innerHTML = showText;
let current = text.substr(index, 1);
if (current === ‘‘, index) + 1;
}
else {
index++;
}
if (index > textArr.length) clearInterval(timer);
}, 100);
//...
input(‘The ZGMF-X20A Strike Freedom Gundam (aka Strike Freedom, Freedom) is the successor of the ZGMF-X10A Freedom.‘);
效果似乎还是不一样,我要的效果应该是输入结束的时候才高亮,我先看看,实现了再补充...
继续补充:
看来只能祭出强无敌的正则匹配了==
//...
const timer = setInterval(() => {
const showText = textArr.slice(0, index).join(‘‘).replace(/\([\s\S]*)\/ig, ‘\$1\‘);
textDom.innerHTML = showText;
let current = text.substr(index, 1);
if (current === ‘‘, index) + 1;
}
else {
index++;
}
if (index > textArr.length) clearInterval(timer);
}, 100);
//...
input(‘The ZGMF-X20A Strike Freedom Gundam (aka Strike Freedom, Freedom) is the successor of the ZGMF-X10A Freedom.‘);
完成
完整代码:
自动打字
>>>
The ZGMF-X20A Strike Freedom Gundam (aka Strike Freedom, Freedom) is the successor of the ZGMF-X10A Freedom.
评论
亲,登录后才可以留言!