tmp.html 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. body{
  8. background: #00FFFF;
  9. }
  10. </style>
  11. </head>
  12. <body>
  13. <!--下载按钮-->
  14. <button onclick="downloadDivContent('#test123')">下载</button>
  15. <div id="test123">
  16. <h1>测试</h1>
  17. <p>测试内容</p>
  18. </div>
  19. <script>
  20. function downloadDivContent(selector) {
  21. // 获取目标div的内容
  22. var targetDiv = document.querySelector(selector).innerHTML;
  23. // 创建Blob对象
  24. var blob = new Blob([targetDiv], { type: 'text/html' });
  25. // 创建下载链接
  26. var downloadLink = document.createElement('a');
  27. downloadLink.href = URL.createObjectURL(blob);
  28. // 设置下载链接的属性
  29. downloadLink.download = 'div_content.html'; // 设置文件名
  30. downloadLink.style.display = 'none'; // 隐藏下载链接
  31. // 将下载链接添加到页面中
  32. document.body.appendChild(downloadLink);
  33. // 模拟用户点击下载链接
  34. downloadLink.click();
  35. // 清理下载链接
  36. document.body.removeChild(downloadLink);
  37. }
  38. </script>
  39. </body>
  40. </html>