打字机文字效果一个接一个地延迟

时间:2018-01-04 09:21:30

标签: javascript jquery

我正在尝试使用打字效果制作2个文本但位于不同的位置。两个文本动画同时开始。如何在经过一段延迟(如5秒或10秒)后启动第二个文本的动画。

https://codepen.io/swaranan/pen/xpLBPr

HTML:

<h1>
  <div class="typewrite" data-period="2000" data-type='[ "Hi, Im John Doe." ]'>
    <span class="wrap"></span>
  </div>
</h1>



<h1>
  <div class="typewrite" data-period="2000" data-type='[ "I Love to Develop." ]'>
    <span class="wrap"></span>
  </div>
</h1>

这是我正在使用的脚本。

var TxtType = function(el, toRotate, period) {
        this.toRotate = toRotate;
        this.el = el;
        this.loopNum = 0;
        this.period = parseInt(period, 10) || 2000;
        this.txt = '';
        this.tick();
        this.isDeleting = false;
    };

TxtType.prototype.tick = function() {
    var i = this.loopNum % this.toRotate.length;
    var fullTxt = this.toRotate[i];

    if (this.isDeleting) {
    this.txt = fullTxt.substring(0, this.txt.length - 1);
    } else {
    this.txt = fullTxt.substring(0, this.txt.length + 1);
    }

    this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';

    var that = this;
    var delta = 200 - Math.random() * 100;

    if (this.isDeleting) { delta /= 2; }

    if (!this.isDeleting && this.txt === fullTxt) {
    delta = this.period;
    this.isDeleting = true;
    } else if (this.isDeleting && this.txt === '') {
    this.isDeleting = false;
    this.loopNum++;
    delta = 500;
    }

    setTimeout(function() {
    that.tick();
    }, delta);
};

window.onload = function() {
    var elements = document.getElementsByClassName('typewrite');
    for (var i=0; i<elements.length; i++) {
        var toRotate = elements[i].getAttribute('data-type');
        var period = elements[i].getAttribute('data-period');
        if (toRotate) {
          new TxtType(elements[i], JSON.parse(toRotate), period);
        }
    }
    // INJECT CSS
    var css = document.createElement("style");
    css.type = "text/css";
    css.innerHTML = ".typewrite > .wrap { border-right: 0.08em solid #fff}";
    document.body.appendChild(css);
};

1 个答案:

答案 0 :(得分:0)

您可以修改onload函数以错开每个打字机效果的开头:

window.onload = function() {
    const OFFSET_MS = 5000; // Your delay in between each element
    var elements = document.getElementsByClassName('typewrite');
    for (var i=0; i<elements.length; i++) {
        var toRotate = elements[i].getAttribute('data-type');
        var period = elements[i].getAttribute('data-period');
        if (toRotate) {
            // Here use a timeout to delay the start
            // Don't forget to use a closure to retain 'i'
            window.setTimeout(((index) => () => {
                new TxtType(elements[index], JSON.parse(toRotate), period);
            })(i), i * OFFSET_MS);
        }
    }
    // {...}
};