JS拷贝内容到剪切板(2019/5/29更新兼容所有浏览器)
const copyTextToClipboard = input => {
if (!input) return false;
const element = document.createElement("textarea");
element.value = input;
// Prevent keyboard from showing on mobile
element.setAttribute("readonly", "");
element.style.contain = "strict";
element.style.position = "absolute";
element.style.left = "-9999px";
element.style.fontSize = "12pt"; // Prevent zooming on iOS
const selection = document.getSelection();
let originalRange = false;
if (selection.rangeCount > 0) {
originalRange = selection.getRangeAt(0);
}
document.body.appendChild(element);
element.select();
// Explicit selection workaround for iOS
element.selectionStart = 0;
element.selectionEnd = input.length;
let isSuccess = false;
isSuccess = document.execCommand("copy");
element.parentNode.removeChild(element);
if (originalRange) {
selection.removeAllRanges();
selection.addRange(originalRange);
}
return isSuccess;
};
module.exports = copyTextToClipboard;
module.exports.default = copyTextToClipboard;
网友评论