我一直在尝试仅使用 js 和 html(如果可能的话,可能还使用 css)创建一个简单的动画。下面附上我的代码,这就是我的想法:
当我按下“单击我”按钮时,它会执行一个打字动画,输入“Lorem Ipsum”。当它完成输入时,其下方会出现一个按钮以继续对话。当您继续时,它会打印出“Dolor sat amet.”,但它只是从“Lorem Ipsum”文本继续。
我期望的是,当我单击“继续”时,它会在新行中打印文本。我还想知道是否可以在对话中途附加图像。例如,如果我想通过添加图像来丰富故事,我希望对话继续输入,然后在其下方会有一个图像,然后再次出现一些对话。
基本上,我想知道是否可以执行“开始”->“继续”按钮->“换行”->“对话”->“图像”->“对话”->“再次继续”
var i = 0;
var txt = 'Lorem Ipsum.';
var speed = 50;
function typingAnim() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typingAnim, speed);
} else {
document.getElementById("continueButton").style.display = "block";
}
}
function continueTyping() {
var otherText = ' Dolor sit amet.';
document.getElementById("continueButton").style.display = "none";
txt += otherText;
i = txt.length - otherText.length;
setTimeout(typingAnim, speed);
}
<button onclick="typingAnim()">Click me</button>
<p id="demo"></p>
<button id="continueButton" style="display: none;" onclick="continueTyping()">Continue</button>
当您想要新行时,您必须创建一个新段落,因为附加到同一段落的innerText将继续当前行。
var txt = 'Lorem Ipsum.';
var speed = 50;
let dialog = document.getElementById("dialog")
function typingAnim(el = null, text = null, image = null) {
el ??= document.getElementById("dialog").children[0]
text ??= txt
el.innerHTML += text.charAt(0);
if(text.length > 1) {
setTimeout(() => typingAnim(el, text.substring(1), image), speed);
}
else if(image) {
let imgEl = document.createElement('img')
imgEl.src = image
dialog.appendChild(imgEl)
}
document.getElementById("continueButton").style.display = "block";
}
function continueTyping() {
var otherText = ' Dolor sit amet.';
let newLine = document.createElement('p')
dialog.appendChild(newLine)
let image = "https://picsum.photos/50/50"
setTimeout(() => typingAnim(newLine, otherText, image), speed);
}
<button onclick="typingAnim()">Click me</button>
<div id="dialog">
<p></p>
</div>
<button id="continueButton" style="display: none;" onclick="continueTyping()">Continue</button>