方法
该方法允许运行命令来操纵可编辑内容区域
// 浏览器中提供复制的方法,复制选中的内容
document.execCommand("copy")
如何复制
这里不得不说select()方法,这个方法是输入框独有的,即<input>和<textarea>,它可以选中输入框中的值,使输入框处于一个聚焦的状态。
步骤:
1、获取输入框
2、调用select()方法获取里面的值
3、使用浏览器提供的方法将其复制
实现
input框实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input value="1234"/>
<button>复制</button>
<script>
let input = document.querySelector('input');
let btn = document.querySelector('button');
btn.onclick = function () {
input.select();
let copy = document.execCommand("copy");
console.log(copy); // true -> 即复制成功 false ->复制失败
}
</script>
</body>
</html>
p标签实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>文本文本文本</p>
<button>复制</button>
<script>
let btn = document.querySelector('button');
btn.onclick = function () {
let aux = document.createElement('input');
aux.setAttribute('value', item.hideId);
aux.select();
document.body.appendChild(aux);
let copy = document.execCommand("copy");
document.body.removeChild(aux);
}
</script>
</body>
</html>