代码之家  ›  专栏  ›  技术社区  ›  Apollo giaset

在两个括号内插入文本-Javascript

  •  1
  • Apollo giaset  · 技术社区  · 11 年前

    我想有一个打字机的效果,这样我就可以从{}开始,单词的每个字母每120毫秒就被打一次。我几乎用以下代码完成了这一点:

    Java脚本

    <script type='text/javascript'>
    var index = 0;
    var text = 'hello'
    
    // Here you can put in the text you want to make it type.
    function type()
    {
        document.getElementById('screen').innerHTML += text.charAt(index);
        index += 1;
        var t = setTimeout('type()',120);
    }
    </script>
    

    HTML格式

    <html>
    <body onload="type()">
    ...
    <div id='screen'>{</div>
    ...
    </body>
    </html>
    

    我的问题是,当单词输入时,没有右括号。因此,在最初的120毫秒之后,它看起来是这样的:{h

    但我希望它看起来像这样

    我怎样才能解决这个问题?

    2 回复  |  直到 11 年前
        1
  •  1
  •   Diego López    11 年前

    在这里查看 http://jsfiddle.net/p56awrea/2

    <script type='text/javascript'>
    var index = 0;
    var text = 'hello'
    var current = ''
    
    // Here you can put in the text you want to make it type.
    function type()
    {
    document.getElementById('screen').innerHTML = '{'+current+'}';
    current+=text.charAt(index);
    index += 1;
    
    if(index==text.length+1){
        current = '';
        index=0;
        setTimeout('type()',2000);
    
    } else {
     setTimeout('type()',120);
    }
    }    
    
    
    </script>
    <body onload="type()">
    ...
    <div id='screen'>{}</div>
    

    编辑 :在循环行为之前添加了2秒延迟

        2
  •  0
  •   wandering-geek    11 年前

    将HTML更改为以下格式如何?

    <html>
    <body onload="type()">
    ...
    <div>&#123;<span id='screen'></span>&#125;</div>
    ...
    </body>
    </html>
    

    我使用的是等效的HTML实体,而不是原始的大括号字符。

    编辑: 将#screen元素从div更改为span,这是一个内联元素

    现在,您将始终在插入的文本周围使用左大括号和右大括号。