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

2026-12-01 0 268

网页设计: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>

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

皮站网 网页制作 网页设计:js复制指定的一段文字 https://www.pizhan.net/307.html

常见问题

相关文章

猜你喜欢
官方客服团队

为您解决烦忧 - 24小时在线 专业服务