javascript實現復制到剪貼板的方法小結
需求
需要一行文字復制到粘貼板上
方法一
適用于localhost 或者是https的網址
const textToCopy = text; // 要復制的內容
navigator.clipboard.writeText(textToCopy)
.then(() => {
message.success('已復制到剪貼板!');
})
.catch(error => {
console.error('復制失敗:', error);
});
方法二
如果你們的網站是http開頭 就只能用這個
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed'; // 防止?jié)L動條跳動
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.opacity = '0'; // 隱藏元素
document.body.appendChild(textArea);
try {
textArea.select(); // 選中內容
document.execCommand('copy'); // 執(zhí)行復制命令
message.success('已復制到剪貼板!');
} catch (error) {
console.error('復制失敗:', error);
} finally {
document.body.removeChild(textArea); // 清理臨時元素
}效果如下

方法補充
將文本復制到剪貼板可以通過5個簡單的步驟完成。
- 創(chuàng)建一個元素并將其附加到我們的 HTML 文檔中。
- 在此中填寫要復制的文本或內容
- 用于選擇此 .HTMLElement.select()
- 復制使用
- 刪除
以下是最簡單的工作版本的代碼。
const copyText = str => {
//Create new element
const elm = document.createElement('textarea');
//Fill the new element with text
elm.value = str;
//Append the new element
document.body.appendChild(elm);
//Select the content of the element
elm.select();
//Copy the content
document.execCommand('copy');
//Remove the element
document.body.removeChild(elm);
};
現在這是一個純函數,它將復制事件上的內容,如 或 。你必須將文本傳遞給它進行復制。
它似乎工作正常,但存在一些問題。
1.我們添加到DOM中的元素將是可見的,這是一個糟糕的用戶體驗。
用戶可能已經選擇了HTML文檔上的一些內容,這些內容將在此操作后刷新,因此我們必須恢復原始選擇。
隱藏已連接的元素。
我們可以設置 樣式,使其在 DOM 上不可見,但仍能夠執(zhí)行其工作。
const copyText = str => {
//Create new element
const elm = document.createElement('textarea');
//Fill the new element with text
elm.value = str;
//Hiding the appended element.
elm.setAttribute('readonly', '');
elm.style.position = 'absolute';
elm.style.left = '-9999px';
//Append the new element
document.body.appendChild(elm);
//Select the content of the element
elm.select();
//Copy the content
document.execCommand('copy');
//Remove the element
document.body.removeChild(elm);
};
恢復原始文檔的選擇
用戶可能已經在DOM上選擇了某些內容,因此將其刪除并不好。
幸運的是,我們可以使用一些新的javascript,如DocumentOrShadowRoot.getSelection(),Selection.rangeCount,Selection.getRangeAt(),Selection.removeAllRanges()和Selection.addRange()來保存和恢復原始文檔選擇。
const copyText = str => {
//Create new element
const elm = document.createElement('textarea');
//Fill the new element with text
elm.value = str;
//Hiding the appended element.
elm.setAttribute('readonly', '');
elm.style.position = 'absolute';
elm.style.left = '-9999px';
//Append the new element
document.body.appendChild(elm);
// Check if there is any content selected previously
const selected =
document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0) // Store selection if found
: false; // Mark as false to know no selection existed before
// Select the <textarea> content
el.select();
// Copy - only works as a result of a user action (e.g. click events)
document.execCommand('copy');
// Remove the <textarea> element
document.body.removeChild(el);
// If a selection existed before copying
if (selected) {
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
};
如果您想通過直接單擊或對其執(zhí)行操作來將文本復制到javascript中的剪貼板,則還有另一種方法。
剪貼板 API 在對象上可用。navigator.clipboard
剪貼板 API 是相對較新的,并非所有瀏覽器都實現它。它適用于Chrome,現代Edge(基于chromium),Firefox和Opera。
我們可以檢查它是否受支持。
if (!navigator.clipboard) {
// Clipboard API not available
return
}
您現在必須了解的一件事是,未經用戶許可,您無法從剪貼板復制/粘貼。
如果您正在閱讀或寫入剪貼板,則權限會有所不同。如果您正在編寫,您所需要的只是用戶的意圖:您需要將剪貼板操作放在對用戶操作的響應中,例如單擊。
將文本寫入剪貼板
假設我們有一個段落元素,我們想要復制其內容。
<p>Master DSA with Javascript</p>
當我們單擊此文本時,我們希望將其復制到剪貼板上。因此,我們?yōu)槠浞峙湟粋€事件偵 聽器。
document.querySelector('p').addEventListener('click', async event => {
if (!navigator.clipboard) {
// Clipboard API not available
return;
}
});
然后,我們調用并將段落元素的文本復制到剪貼板。由于這是一個異步進程,我們將使用異步/等待。navigator.clipboard.writeText()
document.querySelector('p').addEventListener('click', async event => {
if (!navigator.clipboard) {
// Clipboard API not available
return;
}
//Get the paragraph text
const text = event.target.innerText
try {
//Write it to the clipboard
await navigator.clipboard.writeText(text);
//Change text to notify user
event.target.textContent = 'Copied to clipboard';
} catch (err) {
console.error('Failed to copy!', err);
}
})
在剪貼板上編寫內容后,我們也可以從那里閱讀它。
從剪貼板讀取文本
從剪貼板獲取復制的內容。
<p>Master Full stack development with Javascript</p>
當我們單擊此文本時,我們希望將其從我們復制的內容中更改。
document.querySelector('p').addEventListener('click', async event => {
if (!navigator.clipboard) {
// Clipboard API not available
return;
}
});
然后,我們調用并從剪貼板獲取復制的文本。由于這是一個異步進程,我們將使用異步/等待。navigator.clipboard.readText()
document.querySelector('p').addEventListener('click', async event => {
if (!navigator.clipboard) {
// Clipboard API not available
return;
}
try {
//Get the copied text
const text = await navigator.clipboard.readText();
//Pass it to the element.
event.target.textContent = text;
} catch (err) {
console.error('Failed to copy!', err);
}
});
到此這篇關于javascript實現復制到剪貼板的方法小結的文章就介紹到這了,更多相關javascript復制到剪貼板內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JS動態(tài)創(chuàng)建Table,Tr,Td并賦值的具體實現
這篇文章介紹了JS動態(tài)創(chuàng)建Table,Tr,Td并賦值的具體實現,有需要的朋友可以參考一下2013-07-07

