實現點擊不是input或者texterea框的時候復制功能,需求有時復制按鈕需要放置一些特殊的內容,比如一個選中的樹節點,如果需要獲取到它的id
的時候,還有可能會讓你在粘貼前對id進行判斷,如果已經存在亦或者是根節點等特殊情況再次做操作的情況。
主要通過以下兩個API 進行實現,兼容性可以點擊鏈接查看。
當一個HTML文檔切換到設計模式時,document
暴露 execCommand
方法,該方法允許運行命令來操縱可編輯內容區域的元素。(摘自MDN)
是可編輯區域可被操縱。所以需要創建一個臨時的input框或者textarea,如果內容需要保存格式時使用textarea
const btn = document.querySelector("#btn");
btn.addEventListener("click", function() {
// 創建一個input框
const input = document.createElement("input");
// 設置 input框內容
input.setAttribute("value", "copy content");
// 添加到body元素中
document.body.appendChild(input);
// 將新添加進去的input元素進行選中
input.select();
// 為input添加監聽事件方便對剪貼板內容進行二次修改
input.addEventListener("copy", function(event) {
// 使用ClipboardApi來設置剪貼板里的內容
// 參考張鑫旭的博客, 需要的文末有地址
var clipboardData = event.clipboardData || window.clipboardData;
if (!clipboardData) {
return;
}
var text = window.getSelection().toString();
if (text) {
event.preventDefault();
clipboardData.setData("text/plain", text + "\n\n 我是添加進來的內容");
}
});
// 執行復制操作
if (document.execCommand("copy")) {
console.log("復制成功");
} else {
console.log("復制失敗");
}
// document.execCommand('copy') 如果內容復制的不全
// document.execCommand('copy')前先進行document.execCommand('selectAll')選中所有內容即可
// 移除input框
document.body.removeChild(input);
});