无法在 Javascript 中将文本复制到剪贴板

我在尝试了解如何将文本复制到剪贴板的不同方法时遇到了很多问题。如果有人能向我解释为什么我的代码不起作用,我将非常感激。


<!DOCTYPE HTML>

<html dark= "true" style="font-size: 50px;font-family: Roboto, Arial, sans-serif">

<body>

  <textarea id="copytext">ROGER</textarea>

  <div class="button" id="adadad">

    <button onclick="copyS()" id="dlld">

    </button>

  </div>

<p> </p>

<script type=text/javascript">

function copyS{ 

clicked = document.getElementById("dlld");

}

if ("dlld" == clicked){

   var am1 = document.getElementById("copytext");

   document.execCommand("copy");

}

}

</script>

<p> </p>

</body>

</html>


ABOUTYOU
浏览 95回答 4
4回答

人到中年有点甜

好的,我对您的代码做了一些调整,但它现在应该可以工作了。<!DOCTYPE HTML><html dark= "true" style="font-size: 50px;font-family: Roboto, Arial, sans-serif">&nbsp; <body>&nbsp; &nbsp; <textarea id="copytext">ROGER</textarea>&nbsp; &nbsp; <div class="button" id="adadad">&nbsp; &nbsp; &nbsp; <button onclick="copyS()" id="dlld">Copy text</button>&nbsp; &nbsp; </div>&nbsp; &nbsp; <p> </p>&nbsp; &nbsp; <!-- removed the single " at the end of your script tag -->&nbsp; &nbsp; <script type=text/javascript>&nbsp; &nbsp; &nbsp; //added () after you declared your function&nbsp; &nbsp; &nbsp; function copyS(){&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; clicked = document.getElementById("dlld");&nbsp; &nbsp; &nbsp; &nbsp; //added .id to clicked. Not sure why you need to do this, but it works now&nbsp; &nbsp; &nbsp; &nbsp; if ("dlld" == clicked.id){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var am1 = document.getElementById("copytext");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //you need to select before running the .execCommand&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; am1.select();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.execCommand("copy");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script>&nbsp; &nbsp; <p> </p>&nbsp; </body></html>

斯蒂芬大帝

看来您需要select()首先从文本区域获取文本。尝试将您的功能更改为:function copyS{&nbsp;&nbsp; &nbsp;var clicked = document.getElementById("dlld");&nbsp; &nbsp;//if ("dlld" == clicked){ //Not sure you need this&nbsp; &nbsp; &nbsp; var am1 = document.getElementById("copytext");&nbsp; &nbsp; &nbsp; am1.select();&nbsp; &nbsp; &nbsp; document.execCommand("copy");&nbsp; &nbsp;//}}希望有帮助!

拉莫斯之舞

我已经更改了您的代码来完成这项工作。var copiedText = "";document.querySelector("button").onclick = function(e) {&nbsp; copiedText = e.target.previousElementSibling.value;&nbsp; document.execCommand("copy");}document.body.oncopy = function(e) {&nbsp; event.clipboardData.setData('text/plain', copiedText);&nbsp; event.preventDefault();};body {&nbsp; font-size: 50px;&nbsp; font-family: Roboto, Arial, sans-serif;}<textarea>ROGER</textarea><button>Copy</button>

猛跑小猪

尝试这个(<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>)(<script>function copyToClipboard(text) {window.prompt("Copy to clipboard: Ctrl+C, Enter", text);}</script>)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5