共计 1485 个字符,预计需要花费 4 分钟才能阅读完成。
前言
js 复制文本到剪切板有很多方法,很多朋友会用开源库,其实纯 js 的方式实现也很简单。关于复制和剪切板,之前也写过很多文章,例如。
javascript execCommand, 复文本框神器
记录一下 js 光标位置及复制和剪切板
文件上传之剪切板上传及大文件分片上传和断点续传
今天分享一下简单的 copy 方案。
navigator.clipboard.writeText 方案
这个方案不支持 ie, 比较简单
var text = 'Example text to appear on clipboard by haorooms.com';
navigator.clipboard.writeText(text).then(function () {console.log('Haorooms tips: Copying to clipboard was successful!');
},
function (err) {console.error('haorooms tips: Could not copy text:', err);
}
);
document.execCommand(‘copy’)
这些方案博客之前有介绍。可以综合两种方案:
js:
function fallbackCopyTextToClipboard(text) {var textArea = document.createElement('textarea');
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.position = 'fixed';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was' + msg);
} catch (err) {console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {if (!navigator.clipboard) {fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function () {console.log('Async: Copying to clipboard was successful!');
},
function (err) {console.error('Async: Could not copy text:', err);
}
);
}
var copyBobBtn = document.querySelector('.js-copy-haorooms-btn')
copyBobBtn.addEventListener('click', function (event) {copyTextToClipboard(haoroomsinputtext.value);
});
html
此 demo 可以之间 copy 到 html 种之间运行。
正文完