网页设计: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>
© 版权声明
声明:本站所发布的文章,源码等资源均为互联网收集。仅限用于学习和交流,请遵循相关法律法规,请勿商用以及产生法律纠纷本站概不负责!本站遵循CC共享许可协议:BY-NC-SA 4.0如有侵权、后门等请联系本站进行删除
THE END