尝试 运行 循环遍历 querySelectorAll 数组的函数时,setInterval 仅 运行s 一次

setInterval only runs once when trying to run a function that loops through querySelectorAll array

我是新手javascript,所以我可能缺乏基本的了解,但我不明白为什么这段代码会有问题。

我正在尝试创建一个 "console typing effect",这基本上意味着选定的文本应该看起来像是在加载页面后在 "real time" 中键入的。我知道那里有类似的效果,但我想在 vanilla JS(没有框架)中做到这一点。

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

  1. 获取具有 .console-effect Class 的元素并将它们存储在 "elementList"
  2. 遍历元素并在其文本末尾添加光标。
  3. (这里我失败了:() 让光标闪烁

在调试时我发现在遍历游标(使它们闪烁)一次后,方法 "elem.style.opacity" 表示它拥有的元素是 "undefined"...

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]);
    }

};

setInterval() 中的 animateCursor() 中删除 ()

即,像这样:

setInterval(animateCursor, 1000);

括号使函数运行立即生效;将它不带括号实际上将它作为参数变量传递给 setInterval().

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

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

像这样的东西应该可以工作:

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

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