1、演示:
2、代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>一键复制</title>
<style>
.container {
display: flex;
justify-content: center;
>button {
background-color: #fff;
border: 2px solid #ccc;
height: 32px;
border-radius: 5px;
padding: 5px 15px;
}
>span {
line-height: 32px;
}
}
</style>
</head>
<body>
<div class="container">
<span>如:</span>
<span id="text">生活如意,事业高升。</span>
<button id="btn" onclick="copy()">一键复制</button>
</div>
</body>
<script>
function openMessage(value) {
const msg = document.createElement('div');
msg.style.height = '35px';
msg.style.lineHeight = '35px';
msg.style.padding = '5px 10px';
msg.style.position = 'fixed';
msg.style.top = '50%';
msg.style.left = '50%';
msg.style.transform = 'translate(-50%, -50%)';
msg.style.backgroundColor = 'rgba(0, 0, 0, .3)';
msg.style.textAlign = 'center';
msg.style.color = 'white';
msg.style.borderRadius = '15px';
msg.textContent = value;
document.body.appendChild(msg);
setInterval(() => {
document.body.removeChild(msg);
}, 5000);
}
function copy() {
const text = document.getElementById('text')
const textarea = document.createElement('textarea');
textarea.readOnly = 'readonly';
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.value = text.innerText;
document.body.appendChild(textarea);
textarea.select();
const result = document.execCommand('Copy');
if (result) {
// console.log('复制成功');
openMessage('复制成功')
} else {
openMessage('操作失败')
}
document.body.removeChild(textarea);
}
</script>
</html>
本文转载自: https://blog.csdn.net/ggbee_/article/details/134750202
版权归原作者 GGGGGG.enough 所有, 如有侵权,请联系我们删除。
版权归原作者 GGGGGG.enough 所有, 如有侵权,请联系我们删除。