开始10秒倒计时当我单击下载按钮

时间:2014-06-29 07:21:53

标签: javascript jquery

我找到了一个执行此功能的示例,但我想编辑它以在我单击按钮时启动,而不是在文档加载时。

示例:http://jsfiddle.net/rATW7/506/

var downloadButton = document.getElementById("download");
var counter = 10;
var newElement = document.createElement("p");
newElement.innerHTML = "You can download the file in 10 seconds.";
var id;
downloadButton.parentNode.replaceChild(newElement, downloadButton);
id = setInterval(function() {
    counter--;
    if(counter < 0) {
        newElement.parentNode.replaceChild(downloadButton, newElement);
        clearInterval(id);
    } else {
        newElement.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
    }
}, 1000);

2 个答案:

答案 0 :(得分:1)

你可以点击jquery的点击事件,或者在纯javascript中你可以在onclick事件上附加功能。

<button id="btn">click</button>

function startDownload(){
  this.style.display = 'none';
  id = setInterval(function () {
    counter--;
    if (counter < 0) {
        newElement.parentNode.replaceChild(downloadButton, newElement);
        clearInterval(id);
    } else {
        newElement.innerHTML = +counter.toString() + " second.";
    }
}, 1000);
};

 var clickbtn= document.getElementById("btn");
 clickbtn.onclick=startDownload;

Fiddle demo

答案 1 :(得分:1)

目前,您在HTML中的下载按钮正在替换警告段落,倒计时后您再次使用下载按钮替换该段落。

看起来您可以通过在DOM中使用段落并在倒计时后将其替换为下载按钮来避免不必要的html操作。

HTML

<p id='message'>You can download the file in<span id='count'> 10</span> seconds.</p
<button id='start'>Click to start</button

脚本

var message = document.getElementById("message");
var startBtn = document.getElementById("start");
var count = document.getElementById("count");
var timer;
var counter = 10;
var downloadLink = document.createElement("a");
downloadLink.href = "downloadFile.zip";
downloadLink.className += "button";
downloadLink.innerHTML = "Download the file…";
function startDownload() {
 this.style.display = 'none';
 timer = setInterval(function () {
    counter--;
    if (counter < 0) {
        message.style.display = 'none';
        startBtn.parentNode.appendChild(downloadLink);
        clearInterval(timer);
    } else {
        count.innerHTML = " "+counter.toString();
    }
 }, 1000);
};
startBtn.onclick = startDownload;

Demo