我有 DIV 标签,里面有文本。是否可以在具有打字效果的循环中更改文本内容,在其中键入,然后向后删除字母并从新文本开始?这可以用 jquery 实现吗?
最佳答案
一个简单的方法:
const elsTyper = document.querySelectorAll("[data-typer]");
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
const typer = (el) => {
const text = el.dataset.typer;
const tot = text.length;
let ch = 0;
(function typeIt() {
if (ch > tot) return;
el.textContent = text.substring(0, ch++);
setTimeout(typeIt, rand(60, 300));
}());
};
elsTyper.forEach(typer);
/* PULSATING CARET */
[data-typer]:after {
content:"";
display: inline-block;
vertical-align: middle;
width:1px;
height:1em;
background: #000;
animation: caretPulsate 1s linear infinite;
}
@keyframes caretPulsate {
0% {opacity:1;}
50% {opacity:1;}
60% {opacity:0;}
100% {opacity:0;}
}
<span data-typer="Hi! My name is Al. I will guide you trough the Setup process."></span>
<h3 data-typer="This is another typing animated text"></h3>
因此,基本上获取元素的 data-typer
字符串,使用随机的 min-max 超时逐个字符插入。对于同一个 SPAN 的 CSS3 动画 :after
伪元素来说,脉动的“插入符号”毫无意义。
另请参阅:Generate random number between two numbers in JavaScript
关于jquery - 键入动画文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15014066/