javascript - 在函数 showdialog() 上添加打字效果

标签 javascript jquery css html

<body>
<div id="container">
    <div id="background"></div>
  <div id="dialog">
        <p>Hello there!</p>
    </div>
    <div id="button" onclick="showDialog()">
        <img src="images/images/sceond3.jpg" width="126" height="210" alt=""/>
    </div>
</div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>

var counter = 0;
function showDialog() {
    if (counter == 0) {
        $("#dialog p").html("Testing Second Line!");
    }
    if (counter == 1) {
        $("#dialog p").html("Testing Third Line!");
    }
    if (counter == 2) {
        window.location.href = 'third.html';
    }
    //increase counter by 1
    counter++;
}

</script>
</html>

以上是我的代码,请问有没有办法让dialog div中的文字呈现打字效果?我四处搜索,发现大多数教程都是基于单行的,因为我有多行,所以我不确定该怎么做。任何帮助,将不胜感激。谢谢!

最佳答案

检查这个 Fiddle

HTML

<div id="container">
    <div id="background"></div>
    <div id="dialog">
        <p>Hello there!</p>
    </div>
    <div id="button">
        <img src="images/images/sceond3.jpg" width="126" height="210" alt=""/>
    </div>
</div>

JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
    var counter = 0;

    function typeWriter(el,i,str) {
        if (typeof str == "undefined") var str=$(el).text();
        if (typeof i == "undefined") var i=0;
        var text = str.slice(0, ++i);
        if (text != str){
            setTimeout(function(){typeWriter(el,i,str)}, 150);
        }
        $(el).text(text);
    };

    function showDialog() {
        if (counter == 0) {
            $("#dialog p").text("Testing Second Line!");
            typeWriter('#dialog p');
        }
        if (counter == 1) {
            $("#dialog p").text("Testing Third Line!");
            typeWriter('#dialog p');
        }
        if (counter == 2) {
            window.location.href = 'third.html';
        }
        counter++;
    }

    $('#button').on('click',showDialog)
</script>

关于javascript - 在函数 showdialog() 上添加打字效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34528607/

相关文章:

javascript - 如何使用表单输入数据作为React Native中axios请求的输入?

javascript - jQuery 或其他 JS 获取服务器时间并同步滴答时钟并设置事件在准确时间启动

javascript - 仅使 iFrame 内的 div 可见

javascript - css3动画使用html5数据属性

html - 无法通过将鼠标悬停在另一个 div 上来更改 div 样式

html - first child under parent setting margin 的概念基于浏览器中渲染的第一个 child

javascript - 显示无不工作

java - 日期选择器不适用于 jqgrid

JavaScript 音频无法在 jQuery 函数之外播放

html - 试图将一个框 div 放置在另一个框 div 中