方法一:使用range和seletion对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="div">文本</div>
<div onclick="copy('.div')">复制</div>
<script>
function copy(className){
// 创建range对象
let range = document.createRange();
// 传入需要选中的节点
range.selectNodeContents(document.querySelector(className));
var selection = document.getSelection();
// 清空选中的区域
selection.removeAllRanges();
// 添加选中区域
selection.addRange(range);
// 执行复制
document.execCommand('Copy');
}
</script>
</body>
</html>
方法二:使用input或者textarea的select方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="div">
哈哈
</div>
<input type="text">
<div onclick="copy('.div')">复制</div>
<style>
input{position: absolute;left: -1000px;top: -1000px;}
</style>
<script>
/*
这种方法input必须显示出来,以下几种情况都不可以:
display:none
visibility:hidden
width:0
height:0
所以使用定位来达到隐藏的效果
*/
function copy(){
var txt=document.querySelector('.div').innerHTML;
var input=document.querySelector('input');
input.value=txt;
input.select();
// 执行复制
document.execCommand('Copy');
}
</script>
</body>
</html>