【JS】实现剪切板功能
某次面试中被问到过,类似的还有用文本实现js的撤销恢复功能。
核心原理: 利用浏览器提供的copy命令
参考链接
注意: 对ipad、iphone等苹果移动端需做单独处理
document.execCommand("copy");
- 如果是复制输入框里的内容,可以通过 select() 方法,选中输入框的文本,然后调用 copy 命令,复制文本。 注意: select() 方法只对 <input> 和 <textarea> 有效。
var obj= document.getElementById("demo");
obj.select();
document.execCommand("copy");
- 如果是复制非输入框中的文本,则需先创建一个输入框,进行复制后,再清除这个输入框。
var input = document.createElement('input');
input.setAttribute('readonly', 'readonly');
input.setAttribute('value', value);
document.body.appendChild(input);
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
}
document.body.removeChild(input);
完整兼容性代码:
用到的知识点:
1 window.getSelection:返回一个Selection对象,返回用户选择的文本范围或光标当前位置 参考链接
2 document.creatRange():创建一个range对象,选择结点范围 参考链接
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试复制粘贴功能</title>
</head>
<body>
<div>
<label>卡号:</label>
<input type="text" size="20" name="IDCard" id="IDCard">
<button class="copy" onClick="copy('IDCard')">复制</button>
</div>
<div>
<label>用户名:</label>
<input type="text" size="20" name="IDUserName" id="IDUserName">
<button class="copy" onClick="copy('IDUserName')">复制</button>
</div>
<script type="text/javascript">
function copy(type)
{
var textBox = document.getElementById(type);
copyText(textBox);
}
function copyText(node) {
if (!node) {
return;
}
var result;
var tempTextarea = document.createElement('textarea');
document.body.appendChild(tempTextarea);
if (typeof(node) == 'object') {
if (node.value) {
tempTextarea.value = node.value;
} else {
tempTextarea.value = node.innerHTML;
}
} else {
tempTextarea.value = node;
}
//判断设备
var u = navigator.userAgent;
if (u.match(/(iPhone|iPod|iPad);?/i)) {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(tempTextarea);
window.getSelection().addRange(range);
result = document.execCommand('copy');
window.getSelection().removeAllRanges();
} else {
tempTextarea.select();
result = document.execCommand('Copy');
}
document.body.removeChild(tempTextarea);
if (result) {
alert('复制成功', {
removeTime: 1000
})
} else {
alert('复制失败', {
removeTime: 1000
})
}
return result;
}
</script>
</body>
</html>
ps:也可以使用clipboard.js等开源项目。

浙公网安备 33010602011771号