HTML+JS点击复制文字效果(包含点击复制多行)最简单代码

点击复制单行文字

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<span id="biao1">这里是被复制的内容</span>
<input type="button" onClick="copyUrl2()" value="点击复制" class="btn btn-success btn-sm"/>
</body>
<script type="text/javascript">
function copyUrl2()
{
var Url2=document.getElementById("biao1").innerText;
var oInput = document.createElement('input');
oInput.value = Url2;
document.body.appendChild(oInput);
oInput.select(); // 选择对象
document.execCommand("Copy"); // 执行浏览器复制命令
oInput.className = 'oInput';
oInput.style.display='none';
alert('复制成功');
window.location.href="weixin://";//打开微信
}
</script>
</html>

点击复制多行

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<a href="javascript:void(0);" onClick="copyContent()" class="btn btn-success btn-sm"/>点击复制</a>
</body>
<script type="text/javascript">
function copyContent() {
var name = '标题:南京大学在职本科、学历/学位2021春季班招生' + " n";
var url = '原文链接:http://www.baidu.com/html/zsxx/2020/1126/670.html' + " n";
var form = '出处:学友圈' + " n";
var content = name.concat(url, form);
// 使用textarea支持换行,使用input不支持换行
const textarea = document.createElement('textarea');
textarea.value = content;
document.body.appendChild(textarea);
textarea.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
//alert(content);
alert("复制成功");
}
document.body.removeChild(textarea);
}
</script>
</html>
© 版权声明
THE END
点赞64 分享
评论 抢沙发

请登录后发表评论