尝试运行循环遍历querySelectorAll数组

时间:2016-08-01 16:35:30

标签: javascript animation for-loop setinterval

我是javascript的新手,所以我可能缺乏基本的理解,但我不明白为什么此代码中存在问题。

我试图创建一个"控制台输入效果"这基本上意味着所选文本看起来应该像"实时"页面加载后。我知道那里有类似的效果,但我想在vanilla JS(没有框架)中这样做。

到目前为止我做了什么(伪代码):

  1. 使用.console-effect获取元素类将它们存储在" elementList"
  2. 遍历元素并在文本末尾添加光标。
  3. (这里我失败了:()让光标闪烁
  4. 在调试时我发现在循环游标之后(使它们闪烁)一次,方法" elem.style.opacity"说它所拥有的元素是"未定义" ...

    document.body.onload = function() {
    
        function addCursor(element) {
            // Create a Span with the cursor character and give it an class of .cursor
            var newSpan = document.createElement('span'),
                newSpanText = document.createTextNode('|');
            newSpan.appendChild(newSpanText);
            newSpan.className = 'cursor';
    
            //Add newSpan to the element var(passed trough the function)
            element.appendChild(newSpan);
        }
    
        function animateCursor() {
            var cursors = document.querySelectorAll('.cursor');
    
            for (var i = 0; i < cursors.length; i++) {
                cursors[i].style.opacity = '0';
                setTimeout(function() {
                    cursors[i].style.opacity = '1';
                }, 500 );
            }
        }
    
        setInterval('animateCursor()', 1000);
    
        var elementsList = document.querySelectorAll('.console-effect');
        for (var i = 0; i < elementsList.length ; i++) {
            addCursor(elementsList[i]);
        }
    
    };
    

2 个答案:

答案 0 :(得分:0)

()中的animateCursor()移除setInterval()

是的,就像这样:

setInterval(animateCursor, 1000);

括号使函数立即运行;把它放在没有圆括号的地方实际上把它作为参数变量传递给setInterval()

答案 1 :(得分:0)

在Timeout中调用的函数不知道光标:

setTimeout(function() {
  cursors[i].style.opacity = '1';
}, 500 );

这样的事情应该有效:

setTimeout(function() {
  this.style.opacity = '1';
}.bind(cursors[i]), 500 );

即使我确定你会找到一些解释,如果你需要帮助,请告诉我。 顺便说一句:Lambda Ninja将函数作为字符串传递是正确的 - 你应该改变它