JS代码
1 2 3 4 5 6 7 8 9 10
| function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); }
|
示例
1 2 3 4 5 6 7 8 9 10 11 12 13
| <button onclick="download('helloworld.txt','HelloWorld')">下载</button> <script>
function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } </script>
|
效果
点击如下的下载按钮会下载helloworld.txt到浏览器中设置的下载位置.
参考资料
https://www.jianshu.com/p/e856f564e44c