簡體   English   中英

我無法在JavaScript中選擇和復制onclick事件“ span element”

[英]I cannot select and copy onclick event “span element” in javaScript

select()函數適用於輸入標簽,但不適用於跨度標簽。 怎么解決呢?

<span id="selector">paragraph<span>
<script>
  document.getElementById("selector").addEventListner("click", 
  myFunction);

function myFunction(){
  var selectItem = document.getElementById("selector");
  selectItem.select();
  document.execCommand("copy");

  };
 </script>

您可以通過創建虛擬textarea然后復制內容來實現選擇和復制范圍:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test</title> </head> <body> <span id="selector">paragraph</span> <script> document.getElementById("selector").addEventListener("click", copyToClipboard); function copyToClipboard() { var text = document.getElementById('selector').innerHTML; var dummyElm = document.createElement("textarea"); document.body.appendChild(dummyElm); dummyElm.value = text; dummyElm.select(); document.execCommand("copy"); document.body.removeChild(dummyElm); } </script> </body> </html> 

可能的原因是,如MDN站點所述,對select()函數的正確使用不包括span標記:

“ HTMLInputElement.select()方法選擇元素或包含文本字段的元素中的所有文本 。”

MDN參考

您的代碼中的正確用法如下:

 <span id="selector1">paragraph<span> <input id="to_select" type="text" name="text1" value="paragraph"> <input id="selector" type="button" value="Selector"> <script> document.getElementById("selector").addEventListener("click", myFunction); function myFunction(){ var selectItem = document.getElementById("to_select"); selectItem.select(); document.execCommand("copy"); }; </script> 

此外,@ Jason Aller的評論是正確的:“ addEventListner的拼寫不正確”

@gargXImran

根據您的問題,您可以嘗試以下代碼

 document.getElementById("pwd_spn").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"); document.getElementById("copyed_text").innerHTML = textArea.value; textArea.remove(); } 
 <!DOCTYPE html> <html> <body> <span id="pwd_spn" class="password-span">Hii How Are You..</span> <p id="copyed_text"></p> </body> </html> 

希望以上代碼對您有用。

謝謝。

暫無
暫無

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

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