分享几个自己常用的复制代码,复制这东西 做网站还是时常用到的,免得到时候四处去百度了
绑定class属性值进行复制:
<a class="btn" data-clipboard-text="内容">复制一下</a>
<script src="//lib.baomitu.com/clipboard.js/1.7.1/clipboard.min.js"></script>
<script>
var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
alert('复制成功');
e.clearSelection();
});
clipboard.on('error', function(e) {
alert('复制失败');
});
</script>
复制输入框的值:
<input type="text" id="content" value="" required/>
<button type="button" onClick="copyUrl2()">复制一下</button>
<script>
function copyUrl2(){
var urlresult=document.getElementById("content");
urlresult.select(); // 选择对象
document.execCommand("Copy"); // 执行浏览器复制命令
alert("复制成功");
}
</script>
复制传入的参数值:(苹果手机无法复制)
<span onclick="copy('文字内容')">复制一下</span>
<script>
function copy(text) {
const id = 'copy-hide-dom';
let elem = document.getElementById(id);
if (!elem) {
elem = document.createElement('input');
elem.style.height = '0px';
elem.style.outline = '0px';
elem.style.borderWidth = '0px';
elem.style.padding = '0 0';
elem.style.margin = '0 0';
elem.style.position = 'fixed';
document.body.appendChild(elem); }
elem.value = text;
elem.select();
elem.setSelectionRange(0, elem.value.length);
document.execCommand('copy');
alert("复制成功");
}
</script>
如果是静态页面,可代码放置boby的标签属性里,达到点击页面的每个地方都会自动复制
评论
发表评论: