2016-12-17 101 views
1

我在jquery中創建了一個小函數。我想在延遲一段時間後加載它。但我無法延遲執行此代碼。以下是下面的Jquery代碼。在jquery函數中添加延遲

$(function(){ 
     $('.fade').delay(5000).show(); 
     $('.sboxa').delay(5000).show() 
    }) 

這裏是下面的html代碼:

<div class="fade"></div> <div class="sboxa"></div> 

在此功能,請幫助。謝謝

+0

您正在使用什麼版本的jQuery? – Soviut

+0

你想先顯示.fade,然後你想顯示.sboxa類啊? –

+1

你可以發佈一個小提琴 – Ramanlfc

回答

2

要序列動畫,您需要在show()方法中使用回調。在回調內部,您可以使用setTimeout()延遲顯示下一個元素。

$(function(){ 
 
    $('.fade,.sboxa').hide(); 
 
    
 
    $('.fade').show(0, function() { 
 
     setTimeout(function() { 
 
      $('.sboxa').show(); 
 
     }, 2000); 
 
    }); 
 
});
.fade { 
 
    display: block; 
 
    width: 50px; 
 
    height: 50px; 
 
    background: cornflowerblue; 
 
} 
 

 
.sboxa { 
 
    display: block; 
 
    width: 100px; 
 
    height: 100px; 
 
    background: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="fade">fade</div> 
 
<div class="sboxa">sboxa</div>

+0

謝謝你:)所以很多 –

0

@Soviut的答案是正確的,但我認爲你應該添加一個slow參數去顯示或隱藏的方法是這樣的:

$(function(){ 
 
    $('.fade,.sboxa').hide(); 
 
    
 
    $('.fade').show('slow', function() { 
 
     setTimeout(function() { 
 
      $('.sboxa').show('slow'); 
 
     }, 2000); 
 
    }); 
 
});
.fade { 
 
    display: block; 
 
    width: 50px; 
 
    height: 50px; 
 
    background: cornflowerblue; 
 
} 
 

 
.sboxa { 
 
    display: block; 
 
    width: 100px; 
 
    height: 100px; 
 
    background: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="fade">fade</div> 
 
<div class="sboxa">sboxa</div>

希望這有助於!

+0

非常感謝你 –

0

JQuery動畫函數帶有一個可選的函數參數,該參數在動畫完成後執行以允許「鏈接」動畫。不需要手動計時器。

$(function(){ 
 
    $('.fade,.sboxa').hide(); 
 
    
 
    $('.fade').show(2000, function() { 
 
      $('.sboxa').show("slow"); 
 
    }); 
 
});
.fade { 
 
    display: block; 
 
    width: 50px; 
 
    height: 50px; 
 
    background: cornflowerblue; 
 
} 
 

 
.sboxa { 
 
    display: block; 
 
    width: 100px; 
 
    height: 100px; 
 
    background: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="fade">fade</div> 
 
<div class="sboxa">sboxa</div>