簡體   English   中英

如何在JQuery代碼中添加延遲

[英]How to add a delay in JQuery Code

因此,下面的代碼可以使圖像淡入,如何在實際開始淡入之前將其延遲7秒? 這是代碼;

jQuery的:

$(document).ready(function() {
$(".delayImg").each(function() {
    this.onload = function() {
        $(this).animate({opacity: 1}, 8000);
    };
    this.src = this.getAttribute("delayedSrc");
});
});

延遲嗎?

$(document).ready(function() {
  $(".delayImg").each(function() {
    this.onload = function() {
        $(this).delay(7000).animate({opacity: 1}, 8000);
    };
    this.src = this.getAttribute("delayedSrc");
  });
});
 setTimeout(function() {
          // Do something after 7 seconds
    }, 7000);

setTimeout的優點是您可以隨時使用clearTimeout函數取消延遲,如下所示:

var timer = setTimeout(function() {
              // Do something after 7 seconds
        }, 7000);
window.clearTimeout(timer); // Cancel the timer. 

您可以使用jquery delay()setTimeout() 這是同時顯示兩者的jsfiddle

正如David Omid 指出的那樣 ,javascript超時更為靈活,因為您可以取消它。 .delay()方法用於在排隊的jQuery效果之間進行延遲。

HTML:

<img id="delayImg1" class="delayImg" src="imgSource">
<img id="delayImg2" class="delayImg" src="imgSource">

字幕:

var m_delayTimer = null;
var m_delayTime = 5000;
function showImage()
{
    $("#delayImg2").animate({opacity: 1}, 2000)
}

$(document).ready(function() {
    $("#delayImg1").each(function() {
        this.onload = function() {
           $(this).delay(m_delayTime).animate({opacity: 1}, 2000);
        };        
    });
    m_delayTimer = window.setTimeout(showImage,m_delayTime);
});

CSS:

.delayImg
{
    opacity:0;        
}

像這樣的東西。 我認為可以實現settimeout函數。

延遲Javascript

暫無
暫無

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

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