在项目中经常有点击复制一段内容或链接的功能,分享下实现方法:
方法一:
利用input,textarea特有的select()方法,该元素不能设置display:none和 visibility: hidden;否则无效,可以设置opacity: 0;或者利用定位到屏幕之外不可见的地方
<!DOCTYPE html>
<html>
<head lang="en">
<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>
<input type="text" class="copytxt"/>
<script>
function copyUrl() {
document.getElementsByClassName("copytxt")[0].value = "https://www.baidu.com";
var url = document.getElementsByClassName("copytxt")[0];
url.select(); // 选择需要复制内容的对象
document.execCommand("Copy"); // 执行浏览器复制命令
alert("复制成功");
}
</script>
</body>
</html>
缺点:不兼容ios客户端,使用iphone手机复制无效
方法二:利用window对象的getSelection()方法,可兼容pc/ios/Android
<!DOCTYPE html>
<html>
<head lang="en">
<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 = "https://www.baidu.com";
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>
</html>
原文作者技术博客://www.greatytc.com/u/ac4daaeecdfe