Sometimes in order to facilitate the user to quickly copy the content of the page, the general practice is to add a button for the user to click and copy it. Here, the native JavaScript method is used to set the clipboard.
code
copy.html
<!DOCTYPE html>
<html>
<head>
<title>一键复制demo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0,viewport-fit=cover">
<style type="text/css">
*{
padding:0;
margin:0;
}
h2{
text-align: center;
margin-top: 20px;
}
#neirong{
width: calc(90% - 20px);
padding:10px 10px;
margin:20px auto;
background: #eee;
border-radius: 5px;
}
#copy{
border:none;
width: 90%;
height: 45px;
background: #39f;
font-size: 16px;
color: #fff;
font-weight: bold;
border-radius: 5px;
margin: 0 auto;
display: block;
}
</style>
</head>
<body>
<h2>一键复制demo</h2>
<div id="neirong">这是内容这是内容这是内容这是内容</div>
<button id="copy">复制</button>
<script>
function copyArticle(event){
const range = document.createRange();
range.selectNode(document.getElementById('neirong'));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
alert("复制成功");
}
window.onload = function () {
var obt = document.getElementById("copy");
obt.addEventListener('click', copyArticle, false);
}
</script>
</body>
</html>
demo
author
TANKING
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。