HTML 鼠标点击复制元素内容
Intro
- 效果展示
方法封装
copyInnerTextOfCell = (event) => {
let innerText = event.target.innerText;
var tmpInput = document.createElement(“input”);
document.body.appendChild(tmpInput);
tmpInput.value = innerText;
tmpInput.select();
document.execCommand(“cut”); // copy
tmpInput.remove();
alert(“复制成功!” + innerText);
}原理、兼容性、替代方案
官网文档:< https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand>- 实现原理:使用了DOM原生的API
document.execCommand(commandStr)
当一个HTML文档切换到设计模式时,document暴露 execCommand 方法,该方法允许运行命令来操纵可编辑内容区域的元素。 - 兼容性: 已废弃。
- 替代方案/趋势:将来会被 Clipboard替代(需要用户授权后才能运行相关API)。
- 实现原理:使用了DOM原生的API
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wuyujin1997</title>
<script> copyInnerTextOfCell = (event) => { let innerText = event.target.innerText; var tmpInput = document.createElement("input"); document.body.appendChild(tmpInput); tmpInput.value = innerText; tmpInput.select(); document.execCommand("cut"); // copy tmpInput.remove(); alert("复制成功!" + innerText); } </script>
</head>
<body>
<p onclick="copyInnerTextOfCell(event)">这是 p 标签内容</p>
<div onclick="copyInnerTextOfCell(event)">这是 div 标签内容</div>
<span onclick="copyInnerTextOfCell(event)">这是 span 标签内容</span>
</body>
</html>
More
其实核心代码就是通过 execCommand(“copy”) 把某些文本复制到系统剪贴板。
至于是单击触发onClick事件
,
还是双击触发onDbClick事件
,
亦或是鼠标右键触发onContextMenu事件
,
或其他事件,都可以成为这个复制操作的触发点动作。
还没有评论,来说两句吧...