1、JS实现复制div(span)的内容到剪切板的方法
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>复制DIV元素的内容</title>
</head>
<body>
<div id="cent">我是被复制的内容,可以写入系统的剪切板中!</div>
<button id="but">点击我可以复制上面的内容</button>
<script>
//定义一个复制函数
function copyText(text) {
var tag = document.createElement('input');
tag.setAttribute('id', 'copy_input');
tag.value = text;
document.getElementsByTagName('body')[0].appendChild(tag);
document.getElementById('copy_input').select();
document.execCommand('copy');
document.getElementById('copy_input').remove();
}
//点击按钮进行复制
document.getElementById('but').onclick = function () {
//获取DIV的内容
var text = document.getElementById('cent').innerText;
copyText(text);
}
</script>
</body>
</html>
上面的JS复制DIV内容的操作过程,只是模拟了用户手动复制输入框内容的操作,实现的过程可以参考下面的解析!
解析:
1、复制函数中新建立了一个 input 元素,并将要拷贝的内容写放到元素中去。
2、使用 input 元素的 select() 方法来选中 input 内的所有内容!
3、进行内容的拷贝
4:移动新建的 input 元素!
2、JS实现自动复制输入框内容到剪切板的方法
js自动复制输入框内的内容,只需要用 select() 方法来选择 input 元素内的内容,进行拷贝即可,过程非常的简单,可以参考下面的示例代码!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>复制DIV元素的内容</title>
</head>
<body>
<input type="text" value="wenmayi.com" id="host">
<button id="but">点击复制</button>
<script>
//复制逻辑
document.getElementById('but').onclick = function () {
//选择input的内容
document.getElementById('host').select();
//进行copy
document.execCommand('copy');
}
</script>
</body>
</html>