为了账号安全,请及时绑定邮箱和手机立即绑定

使用 JavaScript 将多个标签中特定标签的文本复制到剪贴板

使用 JavaScript 将多个标签中特定标签的文本复制到剪贴板

当年话下 2023-05-25 17:21:53
我想使用 javascript 将输入复制到我的剪贴板,所以有什么办法可以做,谢谢无需输入字段JavaScript 和 HTMLfunction copy(input){     }<p>Text To Copy = hi <button type="button" onclick="copy('hi')">click to copy</button></p>
查看完整描述

3 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

您可以使用navigator.clipboard.writeText将文本复制到剪贴板。


function copy(input) {

  if (navigator.clipboard) {

    navigator.clipboard.writeText(input).then(() => {

      console.log('Copied to clipboard successfully.');

    }, (err) => {

      console.log('Failed to copy the text to clipboard.', err);

    });

  } else if (window.clipboardData) {

    window.clipboardData.setData("Text", input);

  }

}

<p>Text To Copy = hi <button type="button" onclick="copy('hi')">click to copy</button></p>


查看完整回答
反对 回复 2023-05-25
?
慕姐4208626

TA贡献1852条经验 获得超7个赞

function copy_text_fun() {

    //getting text from P tag

    var copyText = document.getElementById("copy_txt");  

    // creating textarea of html

    var input = document.createElement("textarea");

    //adding p tag text to textarea 

    input.value = copyText.textContent;

    document.body.appendChild(input);

    input.select();

    document.execCommand("Copy");

    // removing textarea after copy

    input.remove();

    alert(input.value);

}

<p id="copy_txt">hi</p>

<button  onclick="copy_text_fun()">Copy</button>


查看完整回答
反对 回复 2023-05-25
?
喵喔喔

TA贡献1735条经验 获得超5个赞

请试试这个。也许它会为你工作。


 function myFunction() {

      /* Get the text field */

      var copyText = document.getElementById("myInput");

    

      /* Select the text field */

      copyText.select();

      copyText.setSelectionRange(0, 99999); /*For mobile devices*/

    

      /* Copy the text inside the text field */

      document.execCommand("copy");

    

      /* Alert the copied text */

      alert("Copied the text: " + copyText.value);

    }

 <input type="text" value="Hello World" id="myInput">

    <button onclick="myFunction()">Copy text</button>


查看完整回答
反对 回复 2023-05-25
  • 3 回答
  • 0 关注
  • 132 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信