我无法在JavaScript中选择和复制onclick事件“跨度元素”

时间:2019-09-10 13:39:10

标签: javascript html

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>

3 个答案:

答案 0 :(得分:0)

您可以通过创建一个虚拟的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>

答案 1 :(得分:0)

可能的原因是,如MDN站点所述,正确使用select()函数不包含span标签,

  

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

MDN Reference

在您的代码中的正确用法如下:

<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的拼写不正确”

答案 2 :(得分:0)

@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>

我希望以上代码对您有用。

谢谢。