自动下载

方法1:使用 <a> 标签的 download 属性(推荐)

<button id="downloadBtn1">下载文件</button>

<script>
document.getElementById('downloadBtn1').addEventListener('click', function() {
    // 创建隐藏的链接并触发点击
    const link = document.createElement('a');
    link.href = 'https://example.com/path/to/yourfile.zip';
    link.download = 'filename.zip'; // 指定下载的文件名
    link.style.display = 'none';

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
});
</script>

方法2:直接使用链接样式化按钮

<a href="https://example.com/path/to/yourfile.zip" download="filename.zip" 
   style="text-decoration: none; display: inline-block;">
    <button style="padding: 10px 20px; cursor: pointer;">
        下载文件
    </button>
</a>

使用 download 属性触发多个下载任务

<button id="downloadBtn1">下载文件</button>

<script>
document.getElementById('downloadBtn1').addEventListener('click', function() {
    // 定义多个下载链接
    const files = [
        'https://example.com/path/to/file1.zip',
        'https://example.com/path/to/file2.zip',
        'https://example.com/path/to/file3.zip'
    ];

    // 遍历文件链接,创建并触发多个下载任务
    files.forEach(file => {
        const link = document.createElement('a');
        link.href = file;
        link.download = file.split('/').pop();  // 获取文件名作为下载文件的名称
        link.style.display = 'none';

        document.body.appendChild(link);
        link.click();  // 触发下载
        document.body.removeChild(link);  // 下载完成后移除元素
    });
});
</script>
解释权归© 2026 Luoyihua所有 • CC BY-NC 4.0