本文主要是介绍JS实现复制内容到剪切板,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
说明:借助原生document.execCommand()方法
全部代码如下:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body><div id="txt">需要被复制的内容</div><button onclick="copy()">点击复制</button><script type="text/javascript">const copy = () => {const txt = document.getElementById("txt").innerText; //需要被复制的内容const copyTxt = document.createElement("textarea"); //创建textarea标签临时存储复制的内容copyTxt.setAttribute('readonly', 'readonly'); // 防止IOS系统上弹出软键盘copyTxt.value = txt;document.body.appendChild(copyTxt);copyTxt.select(); // 选择对象document.execCommand("Copy"); // 执行浏览器复制命令copyTxt.style.display = "none";alert("复制成功");};</script></body>
</html>
参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
这篇关于JS实现复制内容到剪切板的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!