隐藏下载链接10秒钟? JS

时间:2011-03-05 21:24:56

标签: javascript timer countdown

嘿,我怎么能隐藏我的下载链接,并制作一个倒计时类型的东西。也许它从10开始倒数​​,一旦完成后会出现下载链接,最好在js中做到这一点吗?

有谁知道怎么做? :d

由于

4 个答案:

答案 0 :(得分:1)

查看setTimeout功能。你可以这样做:

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

setTimeout(displayLink, 10000);

答案 1 :(得分: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开始倒计时的函数。当我们重新计算10时,我们隐藏计数器并显示链接。使用ClearTimeout以便我们在达到十之后不计算。很容易戴尔。

编辑:正如评论中所提到的,这个函数使用jQuery来查找元素。

答案 2 :(得分: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>

答案 3 :(得分: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);
}