js實現點選按鈕複製文字功能
阿新 • • 發佈:2021-10-09
最近遇到一個需求,需要點選按鈕,複製 <p> 標籤中的文字到剪下板
之前做過複製輸入框的內容,原以為差不多,結果發現根本行不通
嘗試了各種辦法,最後使了個障眼法,實現了下面的效果
一、原理分析
瀏覽器提供了 copy 命令 ,可以複製選中的內容
1 |
document.execCommand( "copy" )
|
如果是輸入框,可以通過select()方法,選中輸入框的文字,然後呼叫 copy 命令,將文字複製到剪下板
但是 select() 方法只對 <input> 和 <textarea> 有效,對於 <p> 就不好使
最後我的解決方案是,在頁面中新增一個 <textarea>,然後把它隱藏掉
點選按鈕的時候,先把 <textarea> 的 value 改為 <p> 的 innerText,然後複製 <textarea> 中的內容
二、程式碼實現
HTML 部分
1 2 3 4 5 6 7 8 9 10 |
< style type = "text/css" >
.wrapper {position: relative;}
#input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;} </ style >
< div class = "wrapper" >
< p id = "text" >我把你當兄弟你卻想著複製我?</ p >
< textarea id = "input" >這是幕後黑手</ textarea >
< button onclick = "copyText()" >copy</ button >
</ div >
|
JS 部分
1 2 3 4 5 6 7 8 9 10 |
<script type= "text/javascript" >
function copyText() {
var text = document.getElementById( "text" ).innerText;
var input = document.getElementById( "input" );
input.value = text; // 修改文字框的內容
input.select(); // 選中文字
document.execCommand( "copy" ); // 執行瀏覽器複製命令
alert( "複製成功" );
}
</script>
|
親測,Firefox 48.0,Chrome 60.0,IE 8 都能用
本文來自部落格園,作者:木子歡兒,轉載請註明原文連結:https://www.cnblogs.com/HGNET/p/15387253.html