如何使用纯JavaScript在剪贴板中保存字符串?

问题描述

我想制作一个书签,以保存从Array解析的字符串,我正在寻找一种将const cp = 'text'保存到剪贴板的简单方法。这个问题有什么解决办法吗?在此先感谢:)

解决方法

发布之前先四处看看。这是来自w3schools网站。那里有很多很棒的解释。 https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

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);
}
,

我使用以下功能来实现这一目标。

  const copyToClipboard = (e) => {
    const el = document.createElement('input')
    el.value = window.location // I need a string that was located in the url => you should use whatever value you need,and set the input value to that,obviously.
    el.id = 'url'
    el.style.position = 'fixed'
    el.style.left = '-1000px' // otherwise,sometimes,it creates an input element visible on the screen
    el.setAttribute('readonly',true) // to prevent mobile keyboard from popping up
    document.body.appendChild(el)
    el.select()
    document.execCommand('copy')
  }
,

您可以使用复制事件创建类似的功能

const copyToClipboard = (text) => {
  document.addEventListener('copy',function(e) {
    e.clipboardData.setData('text/plain',text);
    e.preventDefault();
  });
  document.execCommand('copy');
}

answer也很有帮助。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...