1、问题描述
移动端生成链接,自动复制到粘贴板上,借鉴代码如下:
地址:js实现移动端复制功能_Lixw296182的博客-CSDN博客
//复制
copyFun: function() {
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) { //区分iPhone设备
console.log('ios')
window.getSelection().removeAllRanges(); //这段代码必须放在前面否则无效
var Url2 = document.getElementById("copy"); //要复制文字的节点
var range = document.createRange();
// 选中需要复制的节点
range.selectNode(Url2);
// 执行选中元素
window.getSelection().addRange(range);
// 执行 copy *** 作
var successful = document.execCommand('copy');
// 移除选中的元素
window.getSelection().removeAllRanges();
} else {
var text = document.getElementById("copy").innerText;
const textarea = document.createElement("textarea");
textarea.style.position = 'fixed';
textarea.style.top = 0;
textarea.style.left = 0;
textarea.style.border = 'none';
textarea.style.outline = 'none';
textarea.style.resize = 'none';
textarea.style.background = 'transparent';
textarea.style.color = 'transparent';
textarea.value = text; // 修改文本框的内容
document.body.appendChild(textarea);
textarea.select() // 选中文本
try {
const msg = document.execCommand('copy') ?
'successful' : 'unsuccessful';
H.$toast("复制成功");
} catch (err) {
alert('unable to copy', err);
H.$toast("复制失败");
}
document.body.removeChild(textarea)
}
},
2、用了上出代码存在的问题:
document.execCommand()在IOS系统不执行,一直为false,无法复制。
3.解决方法
使用clipboard.js 插件,代码如下:
(1)安装插件
npm install clipboard --save
(2)引用
import ClipboardJS from 'clipboard'
(3)应用
js部分
copyFn(){
let clipboard = new ClipboardJS("#copyBtn");
clipboard.on("success", function(e) {
alert("已将链接复制到粘贴板,赶紧分享给朋友吧");
e.clearSelection();
clipboard.destroy()
});
clipboard.on("error", function(e) {
alert("复制失败!");
e.clearSelection();
});
}
HTML部分
{{comment}}
复制
遇见的问题:
点击复制后,如刷新页面第一次出现一次“已将链接复制到粘贴板,赶紧分享给朋友吧”,第二次出现2次‘已将链接复制到粘贴板,赶紧分享给朋友吧’,第三次出现三次。。。,添加上下面的代码择解决:
clipboard.destroy()
更多问题可参照:clipboard.js — Copy to clipboard without Flashhttps://clipboardjs.com/#example-text
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)