我正在尝试使用我的文本实现打字机效果,其中每个句子(h1标签)被打印,然后文本被清除,第二句被打印。一旦第二句或第三句完成打印,它应该清除并开始循环打印第一句。
我无法清除第一句话,所有文字都被叠加了,“the”这个词也没有出现。
任何想法如何进行?我想将文本保留在HTML中,以便我可以在不同页面上重复使用该脚本。
JSFiddle链接:https://jsfiddle.net/b33uhLL2/
HTML:
<div id="typewriter">
<h1>This<br> is<br> the<br>first<br><span class="highlight">sentence</span></h1>
<h1>This<br> is<br> the<br>second<br>sentence</h1>
</div>
JS:
function setupTypewriter(t) {
var HTML = t.innerHTML;
t.innerHTML = "";
var cursorPosition = 0,
tag = "",
writingTag = false,
tagOpen = false,
typeSpeed = 200,
tempTypeSpeed = 0;
var type = function() {
if (writingTag === true) {
tag += HTML[cursorPosition];
}
if (HTML[cursorPosition] === "<") {
tempTypeSpeed = 0;
if (tagOpen) {
tagOpen = false;
writingTag = true;
} else {
tag = "";
tagOpen = true;
writingTag = true;
tag += HTML[cursorPosition];
}
}
if (!writingTag && tagOpen) {
tag.innerHTML += HTML[cursorPosition];
}
if (!writingTag && !tagOpen) {
if (HTML[cursorPosition] === " ") {
tempTypeSpeed = 0;
} else {
tempTypeSpeed = (Math.random() * typeSpeed) + 50;
}
t.innerHTML += HTML[cursorPosition];
}
if (writingTag === true && HTML[cursorPosition] === ">") {
tempTypeSpeed = (Math.random() * typeSpeed) + 50;
writingTag = false;
if (tagOpen) {
var newSpan = document.createElement("span");
t.appendChild(newSpan);
newSpan.innerHTML = tag;
tag = newSpan.firstChild;
}
}
cursorPosition += 1;
if (cursorPosition < HTML.length - 1) {
setTimeout(type, tempTypeSpeed);
}
};
return {
type: type
};
}
var typer = document.getElementById('typewriter');
typewriter = setupTypewriter(typewriter);
typewriter.type();
CSS:
h1 {
font-family: helvetica;
font-size: 20px;
}
答案 0 :(得分:0)
GreenSock
可能会有运气。
您可以在时间轴中使用.from
。这是一个使用两个标题的起点。
const container = document.querySelector('div')
const h1 = document.querySelector('h1')
const h2 = document.querySelector('h2')
const typewriterTimeline = new TimelineMax({
onStart: () => container.classList.remove('hidden')
})
typewriterTimeline
.add(TweenMax.from(h1, 3, {text: '', delimiter: ' '}))
.add(TweenMax.from(h2, 3, {text: '', delimiter: ' '}))
.hidden {
display: none;
}
<div class='hidden'>
<h1>This is the title</h1>
<h2>This is the subtitle</h2>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/plugins/TextPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>
为了使其更具动态性,您可以循环播放内容并生成时间轴。
希望能帮到你!