簡體   English   中英

如何在頁面加載時延遲此Javascript代碼?

[英]How can I delay this Javascript code at page load?

我想在頁面加載后而不是立即開始延遲此鍵入效果,我該怎么做?

document.addEventListener ('DOMContentLoaded',function(event) {

  var dataText = ["This is a typing effect"];

  function typeWriter(text, i, fnCallback) {
    if (i < (text.length)) {
      document.querySelector("h1").innerHTML = text.substring(0, i+1) +'<span aria-hidden="true"></span>';
      setTimeout(function() {
        typeWriter(text, i + 1, fnCallback)
      }, 75);
    }
    else if (typeof fnCallback == 'function') {
    }
  }
  function StartTextAnimation(i) {
    if (typeof dataText[i] == 'undefined'){
      setTimeout(function() {
        StartTextAnimation(0);
      }, 20000);
    }
    if (i < dataText[i].length) {
      typeWriter(dataText[i], 0, function(){
        StartTextAnimation(i + 1);
      });
    }
  }
  StartTextAnimation(0);
});

因此,您似乎想在頁面加載后將動畫的開始延遲設置的時間而不是將其延遲頁面加載之后。 我們所有人都誤解了這一點,因為前者比后者使用的情況要少得多。

您可以通過更改以下代碼來完成此操作:

    if (i < dataText[i].length) {
      typeWriter(dataText[i], 0, function(){
        StartTextAnimation(i + 1);
      });
    }

...變成這樣:

    if (i < dataText[i].length) {
      setTimeout(function() {
        typeWriter(dataText[i], 0, function(){
          StartTextAnimation(i + 1);
        });
      }, 5000);
    }

...延遲5秒(5000毫秒)

將整個函數放入setTimeout中。

document.addEventListener("DOMContentLoaded",function() {

setTimeout(function(){

 //do your work
}, 2000);
} );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM