使用原生document.execCommand()方法
方法1 在input 輸入框中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input id="demoInput" value="hello world">
<button id="btn">點(diǎn)我復(fù)制</button>
</body>
<script>
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
const input = document.querySelector('#demoInput');
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
console.log('復(fù)制成功');
}
})
</script>
</html>
方法2 在div或者變量中的復(fù)制
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="btn">點(diǎn)我復(fù)制</button>
</body>
<script>
const btn = document.querySelector('#btn');
btn.addEventListener('click',() => {
const input = document.createElement('input');
document.body.appendChild(input);
input.setAttribute('value', '聽(tīng)說(shuō)你想復(fù)制我');
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
console.log('復(fù)制成功');
}
document.body.removeChild(input);
})
</script>
</html>
參考鏈接: