我知道如何以新闻代码类型显示字符(每次延迟显示一个字符),但我似乎知道如何显示多个新闻条目。例如:
H 113和E 114,然后,我会像to
)。
下面是我解决这个问题的微弱尝试(即温室效应)。我可以得到每个字符串,到目前为止,只需在它上做一个console.log。似乎不知道如何从第4步到第6步。
有人把这件事弄清楚吗?
提前谢谢!
<body>
<p class="theText">This is test 1 of the text.</p>
<p class="theText">This is test 2 of the text.</p>
<p class="theText">This is test 3 of the text.</p>
<div id="textScroller"></div>
<script type="text/javascript">
var textScroller = function(scrollContainer){
var container = document.getElementById(scrollContainer);
var nodeContainer = document.getElementsByClassName('theText');
// this function gets only the nodeValues from the nodeContainer array
// and puts them in an array called textArray
var getTextArray = function makeTextArray(theNodeArray){
var textArray = [];
for(var i=0;i<nodeContainer.length;i++){
var container_text = nodeContainer[i].firstChild.nodeValue;
textArray.push(container_text);
}
return textArray;
};
var textArray = getTextArray();
/*
Right now the "showText" function just logs the string of text to the console.
But the function SHOULD
[a] loop through each character in the CURRENT string and
[b] display the current character
[c] check if there are more characters and, if so...
[d] display the next character in 70 milliseconds (i.e. setTimeout or setInterval)
[e] if no more characters, go back to the function (loopArray) and get the next string
*/
function showText(theString){
console.log(theString);
}
// loop through and process each item in the array
var l = 0;
function loopArray(){
var thisString = textArray[l];
showText(thisString);
if(l < textArray.length -1){
setTimeout(loopArray,1000);
}
l++;
}
setTimeout(loopArray,1000);
}
textScroller('textScroller');
</script>
</body>发布于 2011-11-14 03:23:21
您不需要多个循环,只需记住在当前数组项中要执行的字符--如果已经结束,则继续到下一个项。尝试如下所示:
var loopForever = false,
itemIndex = 0,
charIndex = 0;
function loopArray(){
var currentItem = textArray[itemIndex];
if (charIndex >= currentItem.length) {
// move on to next item
if (++itemIndex >= textArray.length) {
// if looping forever go back to start of the item array,
// otherwise return (in which case no new timeout will be set).
if (loopForever)
itemIndex = 0;
else
return;
}
charIndex = 0;
}
showText(currentItem.charAt(charIndex));
// if at the end of the current item then delay 1000ms, otherwise 70ms
setTimeout(loopArray, ++charIndex === currentItem.length ? 1000 : 70);
}
setTimeout(loopArray,1000);以上假设您的其他代码成功地将textArray设置为要显示的字符串数组(在您的示例中,textArray是["This is test 1 of the text.","This is test 2 of the text.","This is test 3 of the text."])。
https://stackoverflow.com/questions/8116805
复制相似问题