页面开发时遇到 PC端复制功能正常,但 手机移动端复制失效的现象
使用的 navigator.clipboard.writeText() 复制方法
可能有的浏览器不支持 navigator.clipboard.writeText()
document.execCommand(‘copy’) 这种复制方式可以,但是好像有的浏览器不支持document.execCommand(‘copy’)
所以添加了判断,如果浏览器支持 document.execCommand(‘copy’) 则使用 document.execCommand(‘copy’) 进行复制;
如果浏览器支持 navigator.clipboard.writeText 则使用navigator.clipboard.writeText修改复制方式
要是两个都不支持,可以不支持的情况下不展示复制模块。
具体情况根据实际情况进行设置~
复制函数
代码示例如下:
// 复制文本内容方法
function copyToClipboard(textToCopy) {
if(document.execCommand('copy')) {
// 创建textarea
var textArea = document.createElement("textarea");
textArea.value = textToCopy;
// 使textarea不在viewport,同时设置不可见
textArea.style.position = "fixed";
textArea.style.opacity = 0;
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((res, rej) => {
// 执行复制命令并移除文本框
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
} else if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
// navigator clipboard 向剪贴板写文本
return navigator.clipboard.writeText(textToCopy);
}
}
复制函数使用方法:
代码示例如下:
// 添加复制点击事件
$('.copyBtn').on('click', function(e) {
var copyBtn = $(this);
var codeElement = e.target.previousSibling;
copyToClipboard(codeElement.innerText).then(() => {
copyBtn.addClass('success').attr('disabled', true).html('复制成功');
setTimeout(function() {
copyBtn.removeClass('success').attr('disabled', false).html('复制');
}, 3000);
});
})