亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法在 Javascript 中將文本復制到剪貼板

無法在 Javascript 中將文本復制到剪貼板

ABOUTYOU 2023-10-30 20:59:49
我在嘗試了解如何將文本復制到剪貼板的不同方法時遇到了很多問題。如果有人能向我解釋為什么我的代碼不起作用,我將非常感激。<!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>
查看完整描述

4 回答

?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

好的,我對您的代碼做了一些調整,但它現在應該可以工作了。


<!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">Copy text</button>

    </div>

    <p> </p>


    <!-- removed the single " at the end of your script tag -->

    <script type=text/javascript>

      //added () after you declared your function

      function copyS(){ 

        clicked = document.getElementById("dlld");

        //added .id to clicked. Not sure why you need to do this, but it works now

        if ("dlld" == clicked.id){

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

          //you need to select before running the .execCommand

          am1.select();

          document.execCommand("copy");

        }

      }

    </script>


    <p> </p>

  </body>

</html>


查看完整回答
反對 回復 2023-10-30
?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

看來您需要select()首先從文本區域獲取文本。嘗試將您的功能更改為:


function copyS{ 

   var clicked = document.getElementById("dlld");


   //if ("dlld" == clicked){ //Not sure you need this

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

      am1.select();

      document.execCommand("copy");

   //}

}

希望有幫助!


查看完整回答
反對 回復 2023-10-30
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

我已經更改了您的代碼來完成這項工作。


var copiedText = "";

document.querySelector("button").onclick = function(e) {

  copiedText = e.target.previousElementSibling.value;

  document.execCommand("copy");

}


document.body.oncopy = function(e) {

  event.clipboardData.setData('text/plain', copiedText);

  event.preventDefault();

};

body {

  font-size: 50px;

  font-family: Roboto, Arial, sans-serif;

}

<textarea>ROGER</textarea>

<button>Copy</button>


查看完整回答
反對 回復 2023-10-30
?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

嘗試這個


(<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>)


查看完整回答
反對 回復 2023-10-30
  • 4 回答
  • 0 關注
  • 230 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號