<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no" name="viewport">
<title>复制粘贴功能</title>
</head>
<body>
<ul>
<li>
<div>
<p>一、采用document.execCommand()原生方法---在input里的值</p>
<input type="text" value="我是input里的原有值" title="test" id="origin-input">
<button id="origin-input-btn">复制input里的值</button>
</div>
</li>
<li>
<div>
<p>二、采用document.execCommand()原生方法---在非input里的值</p>
<p id="not-input">我不是input</p>
<button id="not-input-btn">复制P里的值</button>
</div>
</li>
<li>
<div>
<p>三、采用插件---clipboard.js</p> https://clipboardjs.com/
</div>
</li>
</ul>
</body>
<script>
document.getElementById('origin-input-btn').addEventListener('click',function () {
var originInput = document.querySelector('#origin-input');
originInput.select();
originInput.setSelectionRange(0, originInput.value.length);
if (document.execCommand('copy')) {
document.execCommand('copy');
alert('复制成功');
}else {
alert('你的浏览器不支持复制功能,请升级或更换你的浏览器')
}
})
document.getElementById('not-input-btn').addEventListener('click',function () {
var createInput =document.createElement('input');
createInput.setAttribute('readonly','readonly');
createInput.setAttribute('value',document.getElementById('not-input').innerText);
document.body.appendChild(createInput);
createInput.select();
createInput.setSelectionRange(0, createInput.value.length);
if (document.execCommand('copy')) {
document.execCommand('copy');
alert('复制成功');
}else {
alert('你的浏览器不支持复制功能,请升级或更换你的浏览器')
}
document.body.removeChild(createInput);
})
</script>
</html>