【发布时间】:2016-08-02 00:45:07
【问题描述】:
我是javascript新手,所以可能缺乏基本的了解,但我不明白为什么这段代码会出现问题。
我正在尝试创建“控制台输入效果”,这基本上意味着所选文本应该看起来像是在页面加载后“实时”输入的。我知道那里有类似的效果,但我想在 vanilla JS(无框架)中做到这一点。
到目前为止我所做的事情(伪代码):
- 使用 .console-effect 类获取元素,最终将它们存储在“elementList”中
- 循环遍历元素并在它们拥有的文本末尾添加一个光标。
- (这里我失败了:()使光标闪烁
在调试时我发现在遍历游标(使它们闪烁)一次之后,方法“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]);
}
};
【问题讨论】:
-
这是经典的
closure-in-loop案例。 Creating closures in loops: A common mistake
标签: javascript animation for-loop setinterval