【发布时间】:2018-03-18 10:33:31
【问题描述】:
所以,我是新手,但我试图一次从打印在
中的数组中获取 1 个索引-tag,从 index[0] 开始,沿着数组向下,同时单击一个按钮,使所有文本显示为正在打字。
这是我的数组和我用来返回特定索引的代码,一次一个:
HTML
<button type="button" class="scroll-down" onclick="document.getElementById('foo').innerHTML = nextWord();">Down</button>
<p id="foo" class="chardelay"></p>
JS
var wordArray = [
'Lorem ipsum dolor sit amet',
'consectetur adipiscing elit',
'sed do eiusmod tempor incididunt ut labore'
];
var count = -1;
var nextWord = function() {
return function() {
return wordArray[++count % wordArray.length];
}
}();
var prevWord = function() {
return function() {
return wordArray[--count % wordArray.length];
}
}();
到目前为止一切正常,但如标题中所述,我试图让文本显示为正在打字。我在 CodePen 上找到了以下代码。它使打印的文本出现打字机效果。唯一的问题是所有的索引都被打印出来了,只是它们之间有一点延迟:
var aText = new Array(
"There are only 10 types of people in the world:",
"Those who understand binary, and those who don't"
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter()
{
sContents = ' ';
iRow = Math.max(0, iIndex-iScrollAt);
var destination = document.getElementById("foo");
while ( iRow < iIndex ) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
if ( iTextPos++ == iArrLength ) {
iTextPos = 0;
iIndex++;
if ( iIndex != aText.length ) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}
但我希望仅在单击上面的按钮时打印每个索引(但具有 CodePen 代码提供的甜美打字机效果)。有没有办法将我在 CodePen 上找到的代码与我的代码一起使用/在我的代码中使用,或者我应该尝试另一种方法来解决这个问题?
【问题讨论】:
-
能否请您链接 CodePen
-
你是这个意思吗? github.com/mattboldt/typed.js
标签: javascript html arrays onclick