共计 1010 个字符,预计需要花费 3 分钟才能阅读完成。
导读 | 这篇文章主要为大家介绍了 JavaScript 实现一键复制内容,document.execCommand 原生 JS 设置剪贴板的实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪 |
引言
有时候为了方便用户快速复制页面的内容,一般的做法就是添加一个按钮给用户点击一下就复制下来了,这边使用 JavaScript 原生的方法进行设置剪贴板。
代码
copy.html
一键复制 demo | |
*{ | |
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; | |
} | |
一键复制 demo | |
这是内容这是内容这是内容这是内容 | |
复制 | |
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); | |
} |
实现效果
以上就是 JavaScript 实现一键复制内容剪切板的详细内容。
正文完
星哥玩云-微信公众号
