原生 js 實現點擊按鈕複製文本

最近遇到一個需求,需要點擊按鈕,複製 標籤中的文本到剪切板

之前做過複製輸入框的內容,原以爲差不多,結果發現根本行不通

嘗試了各種辦法,最後使了個障眼法,實現了下面的效果

原生 js 實現點擊按鈕複製文本

在這裏插入圖片描述
一、原理分析

瀏覽器提供了 copy 命令 ,可以複製選中的內容

document.execCommand(“copy”)
如果是輸入框,可以通過 select() 方法,選中輸入框的文本,然後調用 copy 命令,將文本複製到剪切板

但是 select() 方法只對 和 有效,對於

就不好使

最後我的解決方案是,在頁面中添加一個 ,然後把它隱藏掉

點擊按鈕的時候,先把 的 value 改爲

的 innerText,然後複製 中的內容

二、代碼實現

HTML 部分

複製代碼

我把你當兄弟你卻想着複製我?

這是幕後黑手 copy
複製代碼

JS 部分

複製代碼

複製代碼

親測,Firefox 48.0,Chrome 60.0,IE 8 都能用

三、一鍵複製

分享一個自己工作中用到的一鍵複製方法

複製代碼
/**

一鍵粘貼
@param {String} id [需要粘貼的內容]
@param {String} attr [需要 copy 的屬性,默認是 innerText,主要用途例如賦值 a 標籤上的 href 鏈接]
range + selection
1.創建一個 range
2.把內容放入 range
3.把 range 放入 selection
注意:參數 attr 不能是自定義屬性
注意:對於 user-select: none 的元素無效
注意:當 id 爲 false 且 attr 不會空,會直接複製 attr 的內容
*/
copy (id, attr) {
let target = null;

if (attr) {
target = document.createElement(‘div’);
target.id = ‘tempTarget’;
target.style.opacity = ‘0’;
if (id) {
let curNode = document.querySelector(’#’ + id);
target.innerText = curNode[attr];
} else {
target.innerText = attr;
}
document.body.appendChild(target);
} else {
target = document.querySelector(’#’ + id);
}

try {
let range = document.createRange();
range.selectNode(target);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand(‘copy’);
window.getSelection().removeAllRanges();
console.log(‘複製成功’)
} catch (e) {
console.log(‘複製失敗’)
}

if (attr) {
// remove temp target
target.parentElement.removeChild(target);
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章