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

Start 10 sec countdown When i click Download Button

本文关键字:下载 按钮 10秒 倒计时 开始      更新时间:2023-09-26

我找到了一个例子来做这个函数,但我想编辑它,当我点击按钮时开始,而不是在文档加载

示例: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);

你可以在jquery中添加onclick事件,或者在纯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;
<<p> 小提琴演示/strong>

目前你在你的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;
演示