2011-03-05 66 views
1

嘿,我怎麼能隱藏我的下載鏈接,並做出倒數類型的東西。也許它從10倒數,一旦它完成,下載鏈接出現,最好在js中做到這一點?隱藏下載鏈接10秒? js

沒有人知道如何做到這一點? :d

感謝

+1

瑞安米切爾的答案是正確的,但如果你不保護在服務器端的鏈接,持續10秒爲好,你的下載保護將是幼稚容易旁路。 – 2011-03-05 21:45:03

回答

1

你可以使用setInterval。 setInterval的行爲就像一個定時器,您可以定期運行某個函數。這樣的事情應該做的工作(未經測試):

$(".link").hide(); 

var iteration = 0; 
var timer = setInterval(function() { 
    if(iteration++ >= 10) { 
     clearTimeout(timer); 
     $(".link").show(); 
     $(".counter").hide(); 
    } 

    $(".counter").text(10 - iteration); 
}, 1000); 

這最初將隱藏下載鏈接和運行一個函數每秒從10倒計時當我們reaced十個,我們躲在櫃檯,並顯示該鏈接。我們使用了ClearTimeout,以便在我們達到10之後不計算在內。容易如戴爾。

編輯:正如在評論中提到的,這個函數使用jQuery來查找元素。

+0

你應該補充說這段代碼使用了jQuery。 – Lekensteyn 2011-03-05 21:44:47

+0

@Lekensteyn當然。 – alexn 2011-03-05 21:46:15

1

看看在setTimeout功能。你可以這樣做:

function displayLink() { 
    document.getElementById('link_id').style.display = 'block'; 
} 

setTimeout(displayLink, 10000); 
1

完整的示例:

<span id="countdown"></span> 
<a id="download_link" href="download.zip" style="display:none;">Download</a> 
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript> 
<script type="application/javascript"> 
(function(){ 
    var message = "%d seconds before download link appears"; 
    // seconds before download link becomes visible 
    var count = 10; 
    var countdown_element = document.getElementById("countdown"); 
    var download_link = document.getElementById("download_link"); 
    var timer = setInterval(function(){ 
     // if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed 
     if (count) { 
      // display text 
      countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count); 
      // decrease counter 
      count--; 
     } else { 
      // stop timer 
      clearInterval(timer); 
      // hide countdown 
      countdown_element.style.display = "none"; 
      // show download link 
      download_link.style.display = ""; 
     } 
    }, 1000); 
})(); 
</script> 
0
var WAIT_FOR_SECONDS = 10; 
var DOWNLOAD_BUTTON_ID = "btnDownload"; 

if (document.body.addEventListener) { 
    document.body.addEventListener("load", displayDownloadButton, false); 
} else { 
    document.body.onload = displayDownloadButton; 
} 

function displayDownloadButton(event) { 
    setTimeout(function() { 
     _e(DOWNLOAD_BUTTON_ID).style.display = ""; 
    }, WAIT_FOR_SECONDS*1000); 
} 

function _e(id) { 
    return document.getElementById(id); 
}