2011-01-27 115 views
4

Hy,重定向10,.. 9,...腳本

我有10秒的時間。延遲頁面。

var t = window.setTimeout('redirect(strUrl)', 11000); 

和功能重定向(strUrl)少了點document.location

將是很好,如果我有一個小消息,在我的頁面底部顯示,例如:在10秒重定向...

「一秒鐘後說的setTimeout炒魷魚」

...重定向到命運的9秒..

ps。並且最後的點從左到右你知道它。 .. ...

我自己可能會找出如何讓每秒超時,只是用jquery改變了數字...如果這是可能的。

+0

這是一個美國國家航空航天局的分配​​;)? – 2011-01-27 11:27:22

+0

ha:D不,只是有自己的問題。 ..首先檢查答案 – PathOfNeo 2011-01-27 11:32:09

回答

6
var timeout = 11; // in seconds 

var msgContainer = $('<div />').appendTo('body'), 
    msg = $('<span />').appendTo(msgContainer), 
    dots = $('<span />').appendTo(msgContainer); 

var timeoutInterval = setInterval(function() { 

    timeout--; 

    msg.html('Redirecting in ' + timeout + ' seconds'); 

    if (timeout == 0) { 
     clearInterval(timeoutInterval); 
     redirect(strUrl); 
    } 

}, 1000); 

setInterval(function() { 

    if (dots.html().length == 3) { 
     dots.html(''); 
    } 

    dots.html(function(i, oldHtml) { return oldHtml += '.' }); 
}, 500); 

See it on jsFiddle

如果你想有秒的東西,代替上面相應的行...

msg.html('Redirecting in ' + timeout + ' second' + ((timeout != 1) ? 's' : '')); 

當然,這個效果很好的英語,但可能是不與其他容易語言。

+0

感謝您的詳細解決方案。橫衝直撞! – PathOfNeo 2011-01-27 13:43:59

2

你可以通過創建一個div來完成,你可以用bottomleft座標絕對定位,並且通過在每秒循環來更新div中的文本。事情是這樣的:

function redirect(strurl) { 
    var seconds = 10; 
    var div = $("<div/>").css({ 
    position: "absolute", 
    left: "0px", 
    bottom: "0px" 
    }).appendTo(document.body); 

    continueCountdown(); 

    function continueCountdown() { 
    --seconds; 
    if (seconds >= 0) { 
     div.text("...Redirecting in " + seconds + " seconds..."); 
     setTimeout(continueCountdown, 1000); 
    } 
    else { 
     // Redirect here 
     document.location = strurl; 
    } 
    } 
} 

Live example

需要注意的是,這將是不精確,因爲超時不一定會在正好一秒。但它會很接近。

2

試試這個:

var count=10; 

window.setTimeout(function(){redirect(url)}, 1000); 

function redirect(url){ 
    if(--count==0){ 
     location.href=url; 
     return; 
    } 
    $("#DIV_TO_DISPLAY_MESSAGE").text("redirecting in " + count+" secs."); 
    window.setTimeout(function(){redirect(url)}, 1000); 
} 
1

定義一個變量秒的數量,並在的setTimeout(...,1000)通話功能whitch會降低秒的數量,一些-DIV/SPAN的變化內容。 ..,如果秒= 0重定向。