tags:
- js
- ctrl+c
網頁內容復制粘貼(三種方案 兼容多種瀏覽器)
對網頁上的內容實現復制粘貼的功能
痛點:需要支持多種不同的瀏覽器 主要有IE,Firefox
- IE瀏覽器下的解決方案:
window.clipboardData.setData("Text", text);
- 通用瀏覽器的解決方案:
選中元素之后執行:
document.execCommand('copy')
- Firefox下的解決方案
兩種折中的方案
a. 監聽hover事件 當鼠標移動至需要復制的文本上時 用戶按下ctrl+c 實現復制
b.window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
彈出框內容為選中的文案,用戶按下ctrl+c 實現復制
整合之后的代碼為
function copyToClipboard(text) {
if (window.clipboardData) { // Internet Explorer
window.clipboardData.setData("Text", text);
} else {
var textArea = document.createElement("textarea");
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
if (!document.execCommand('copy')) {
copyToClipboardMozilla(text);
} else {
showInfo("提示", "復制成功")
}
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
}
function copyToClipboardMozilla(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
$(".copy").on("mouseenter", function () {
$(this).css("background-color", "#c8c9c8");
$(this).focus();
var textArea = document.createElement("textarea");
textArea.style.background = 'transparent';
textArea.id = "copyContent";
textArea.value = $(this).text();
document.body.appendChild(textArea);
textArea.select();
})
$(".copy").on("mouseleave", function () {
$(this).css("background-color", "");
document.body.removeChild(document.getElementById("copyContent"));
})
參考資料:
- 幾個通用的解決復制的方法:
-
document.execCommand API
W3C API - How do I copy to the clipboard in JavaScript?
- How does Trello access the user's clipboard?
- 20 行 JS 代碼,實現復制到剪貼板功能
兼容處理了瀏覽器的復制功能,有更好的方案解決歡迎留言聯系
未經作者允許 請勿轉載,謝謝 :)