原生js实现复制功能

   

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
</head>

<body>
<div id="copy">这是需要复制的内容部</div>
<br>
<input type="button" name="" value="点击复制" onclick="copyToClipboard('copy')">
<br>
<br>
<input type="text" name="" placeholder="粘贴到这里试试">
</body>
<script>

function copyToClipboard(elementId) {
// 创建元素用于复制
var aux = document.createElement("input");

// 获取复制内容
var content = document.getElementById(elementId).innerHTML || document.getElementById(elementId).value;

// 设置元素内容
aux.setAttribute("value", content);

// 将元素插入页面进行调用
document.body.appendChild(aux);

// 复制内容
aux.select();

// 将内容复制到剪贴板
document.execCommand("copy");

// 删除创建元素
document.body.removeChild(aux);

//提示
alert("复制内容成功:" + aux.value);
}
</script>

</html>

猜你喜欢

转载自www.cnblogs.com/hanling1103/p/9371907.html