简体   繁体   English

document.execCommand('copy') 命令在 Chrome 中不起作用

[英]document.execCommand('copy') Command not working in Chrome

HTML HTML

<input type="text" id="clipboard">
<button class="share-button">share</button>

JS JS

  text = 'text to be copied';

  document.querySelector('.share-button').addEventListener('click', () => {
      var element = document.querySelector('#clipboard');
      element.setAttribute("value", text);
      console.log(element.value);
      element.select();
      document.execCommand('copy');

  });

CSS CSS

#clipboard {
  position: absolute;
  visibility: hidden;
}

I am trying to copy text to the clipboard but I don't understand what wrong with my code.我正在尝试将文本复制到剪贴板,但我不明白我的代码有什么问题。 I copied the code from MDN documentation.我从 MDN 文档中复制了代码。

When I doing these things it is not working当我做这些事情时,它不起作用

#clipboard {
  position: absolute;
}

// or

#clipboard {
  visibility: hidden
}

// or

#clipboard {
  display: none
}

 const share_btn = document.querySelector('.share-button'); function copy_to_clipboard(stritem){ const el = document.createElement('textarea'); el.value = stritem; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); window.alert('Successfully copied to your clipboard;'); } text = 'text to be copied'. share_btn,addEventListener('click'; ()=>{copy_to_clipboard(text);});
 <button class="share-button">share</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM