复制文本到剪贴板及获取网站链接
一、点击按钮复制文本到剪贴板
#text {
width: auto;height: 50px;
padding: 10px;
background: #00BFFF;
font-size: 30px;
}
<div>
<textarea id="text">MrFlySand.github.io</textarea>
<button onclick="copyText()">复制文本</button>
</div>
文本最好在textarea标签中
function copyText() {
var t = document.getElementById("text");
t.select();
document.execCommand("copy");// 执行浏览器复制命令
alert("复制成功");
}
二、点击按钮复制当前网站链接到剪贴板
修改textarea元素的value(值),复制到剪贴板
.wrapper{
position: relative;
}
.wrapper>textarea{
position: absolute;
left: 0;
}
.wrapper>#word{
opacity: 0;/*元素的不透明度*/
}
button{
margin: 10px;
}
<div class="wrapper">
<textarea id="word"></textarea>
<button onclick="copyHref()">复制链接</button>
</div>
function copyHref(){
var word = document.getElementById("word");
word.value = document.location.href; // 获取当前网站链接
word.select(); //选中文本
document.execCommand("copy");
alert("复制成功");
}