脚本无法在chrome中正确显示

时间:2014-04-11 14:18:31

标签: javascript google-chrome

我正在使用一个在Firefox和IE中正常工作的简短JavaScript函数,并且在chrome中无法正确显示。 该函数只是在页面上键入一个文本块。在FF和IE中,它输入正常。在Chrome中,它会在中途停止,但不会完成。

脚本是:

var index = 0;
var text ='text to get typed goes here';

function type() {
    document.getElementById('screen').innerHTML += text.charAt(index);
    index += 1;
    var t = setTimeout('type()',50);
}

它在页面上被调用

div align="left" class="normtext" id='screen'

有没有人知道为什么这不适用于Chrome?感谢。

1 个答案:

答案 0 :(得分:0)

你的setTimeout需要一个闭包,因为它在全局/窗口范围内调用它的函数。这将阻止在某些情况下将功能识别为已定义。

这是工作代码:

var index = 0;
var text ='text to get typed goes here';

function type() {
    if (index < text.length) { // Don't go on typing after finishing.
        document.getElementById('screen').innerHTML += text.charAt(index);
        index += 1;
        var t = setTimeout(function () {
            type();
        },50);
    }
}
type();

您还可以在此处查看示例:http://jsfiddle.net/harveyramer/PF4Tx/

相关问题