分享一个js复制文本的函数,兼容web、wap、微信等多终端html。之前因为有项目需要用到点击文本直接复制功能,找了很多都是用jq的扩展或者用其他扩展js引入的,但是效果并不是很好用。
现在分享一个目前用得比较顺手的方法:
function copy() {
const range = document.createRange();
range.selectNode(document.getElementById('wxNumber'));//需要复制的内容
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
alert("复制成功!打开微信添加好友");
}指定其他的对象也可以的:
function copy() {
var className = 'content';
const range = document.createRange();
range.selectNode(document.getElementsByClassName(className)[0]);//需要复制的内容,需要的是range
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
layer.msg("复制成功!",{icon:6,time:1000});
}自己优化升级版,自带提示:
/**
* 复制内容
* @param obj 复制的对象,如this
* @param className 根据类查询
* @param expire 毫秒
*/
function copy(obj,className,expire) {
if (!expire){
expire = 1000;
}
const range = document.createRange();
const selection = window.getSelection();
if (className && className !=='undefined'){
range.selectNode(document.getElementsByClassName(className)[0]);//需要复制的内容,需要的是range
}else {
range.selectNode(obj); //需要复制的内容
}
if (selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
var bsClassName = 'bs-alert-copy';
var p= document.createElement('p');
p.className = bsClassName;
p.innerHTML = '<p class="" style="position: fixed; top: 30%;left: 45%; text-align: center; vertical-align: middle; background: #0000006e;color: white; padding: 10px;border-radius: 2px;">复制成功</p>';
document.getElementsByTagName('body')[0].append(p);
var node = document.getElementsByClassName(bsClassName)[0]
setTimeout(function () {
document.getElementsByTagName('body')[0].removeChild(node)
},expire)
}
//使用方式1
<span onclick="copy(false,'tihuo-code',2000)" class="tihuo-code">628248</span>
//使用方式2
<span onclick="copy(this)" class="tihuo-code">628248</span>