簡體   English   中英

無法將文本復制到剪貼板但 innerHTML 讀取內容

[英]cannot copy text to clipboard but innerHTML reads content

我正在嘗試復制 span 元素的內容,但到目前為止我失敗了,chrome 中沒有錯誤:

 const element = document.getElementById("element"); console.log(element.innerHTML); //consoles Data //below doesn't copy contents of the element to clipboard const node = document.createRange(); node.selectNode(element); window.getSelection().removeAllRanges(); window.getSelection().addRange(node); document.execCommand("copy");
 <span id="element">Data</span>

因為我可以通過 innerHTML 查看元素的內容,所以我認為該元素確實是可訪問的。 為什么我不能復制文字?

回答了你的問題:

 document.getElementById("cp_btn").addEventListener("click", copy_password); function copy_password() { var copyText = document.getElementById("pwd_spn"); var textArea = document.createElement("textarea"); textArea.value = copyText.textContent; document.body.appendChild(textArea); textArea.select(); document.execCommand("Copy"); textArea.remove(); }
 <span id="pwd_spn" class="password-span">Test</span> <button id="cp_btn">Copy</button>

您的代碼中唯一錯誤的是沒有按鈕。 沒有一個是不可能復制文本的,以防止剪貼板中毒。 以下內容應該適合您:

 function copy() { const element = document.getElementById("element"); const node = document.createRange(); node.selectNode(element); window.getSelection().removeAllRanges(); window.getSelection().addRange(node); document.execCommand("copy"); }
 <span id="element">Data</span> <button onclick="copy()">Copy</button>

但是,我認為實現相同目的的一種更簡單的方法是( 將文本從 <span> 復制到剪貼板):

 function copy() { var copyText = document.getElementById("element"); var textArea = document.createElement("textarea"); textArea.value = copyText.textContent; document.body.appendChild(textArea); textArea.select(); document.execCommand("Copy"); textArea.remove(); }
 <span id="element">Data</span> <button onclick="copy()">Copy</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM