我知道如何以新闻自动收录方式显示字符(延迟时间一次显示1个字符),但我似乎可以弄清楚如何显示 多个新闻项目。例如:
以下是我解决这个问题的微弱(即新手)尝试。我可以得到每个字符串,到目前为止只做一个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>
答案 0 :(得分:1)
你不需要多个循环,你只需要记住当前数组项中你正在使用哪个角色 - 如果你已经离开了最后,那么继续前进到下一个项目。尝试以下内容:
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."]
为{{1}})。