网页设计:js复制指定的一段文字,javascript代码

网页设计:js复制指定的一段文字

关键代码:

<script>
function copyUrl(){
document.getElementsByClassName("copytxt")[0].innerText = "这里输入要复制的内容";
const range = document.createRange();
range.selectNode(document.querySelector(".copytxt"));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('Copy');
alert("复制成功");
}
</script>

完整代码

<head lang="zh-cn">
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0' />
<title></title>
<style>
body{
padding: 20px;
text-align: center;
}
.copytxt{
opacity: 0;/*不可以用display:none和 visibility: hidden;*/
}
</style>
</head>
<body>
<a href="javascript:;" onclick="copyUrl()">点我复制</a>
<span class="copytxt">大众点评内容</span>
<script>
function copyUrl(){
document.getElementsByClassName("copytxt")[0].innerText = "这里输入要复制的内容";
const range = document.createRange();
range.selectNode(document.querySelector(".copytxt"));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('Copy');
alert("复制成功");
}
</script>
</body>
© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享