这段代码应该每200 MilliSecond键入字符串myText
中的一个字母,以类似于type Effect,但它的类型是undefinded
而不是letters
。
var myText = "loremloremloremloremloremloremloremloremloremloremloremlorem",
myButton = document.getElementById("Button"),
result = document.getElementById("type"),
i;
myButton.onclick = function (){
"use strict";
setInterval(function(){
result.textContent += myText[i];
i++;
}, 200);
}
<p id="type"></p>
<button id="Button">Click!</button>
发布于 2020-07-20 23:04:11
您缺少i= 0,初始值
发布于 2020-07-20 23:10:17
试一试
result.textContent += myText.substring(i, i+1);
在JS (简短而不精确的解释)中,您试图使用myText[1]
访问对象字符串(MyText)的属性"1“。
发布于 2020-07-20 23:14:40
您可以将其封装在一个可重用的函数中,并添加一个检查,以查看已写入了多少字符。
一旦到达字符串的末尾,您就可以取消间隔。
您可以通过在超时后传递附加参数来将附加参数包含在间隔内。
const myText = "loremloremloremloremloremloremloremloremloremloremloremlorem";
document.getElementById('my-button').onclick = (e) => {
autoType(myText, '#type-1', 50);
autoType(myText, '#type-2', 100);
}
function autoType(text, target, timeout) {
target = typeof target === 'string' ?
document.querySelector(target) : target;
let intervalId = setInterval((options) => {
if (options.index >= text.length - 1) {
clearInterval(intervalId);
}
target.textContent += text[options.index];
options.index++;
}, timeout, { index: 0 });
}
<p id="type-1"></p>
<p id="type-2"></p>
<button id="my-button">Click!</button>
https://stackoverflow.com/questions/62998312
复制相似问题