2011-03-05 63 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); 
}