<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Js复制代码 </title>
</head>
<body>
<input id='biao1' value="你好.要copy的内容!">
<input type="button" onclick="oCopy();" value='hhhh'/>
<script language="javascript">
function oCopy(){
var obj=document.getElementById("biao1");
obj.select();
document.execCommand("Copy")
}
</script>
</body></html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Js复制代码 js模拟选中,按键粘贴(可用于隐藏域粘贴)</title>
</head>
<body>
<p>啊啊啊</p>
<button id="btn">点击复制</button>
<script type="text/javascript">
var btn = document.getElementById("btn");
btn.addEventListener('click', copyContent);
function copyContent () {
let val = document.querySelector("p").innerText; // 要复制的内容
document.addEventListener('copy', save); // 监听浏览器copy事件
document.execCommand('copy'); // 执行copy事件,这时监听函数会执行save函数。
document.removeEventListener('copy', save); // 移除copy事件
// 保存方法
function save(e) {
e.clipboardData.setData('text/plain', val); // 剪贴板内容设置
e.preventDefault();
}
}
</script>
</body></html>
该方法实现js模拟选中,按键粘贴(可用于隐藏域粘贴) ,比如,表格相关数据列数据需复制,此时将数据放入隐藏域中,对该隐藏域进行复制,即可复制成功
法二:使用插件clipboard