javascript - 如何将div内容以字符串格式复制到剪贴板

标签 javascript reactjs

<分区>

我正在使用 ReactJS,当用户点击一个按钮时,我想将一些 div 内容复制到剪贴板。

我不明白为什么这段代码没有导致数据被复制到剪贴板。 我正在从 redux store 提供值(value),当它真正是从 div 应对内容时

componentDidUpdate(prevProps, prevState, snapshot) {
  console.log("value to copy is-->", this.props.copy);
  var copyText = document.getElementById("myInput");

  /* Select the text field */

  console.log("copyText-->", copyText);
  console.log("document-->", document);
  /* Copy the text inside the text field */
  document.execCommand("copy");
}

最佳答案

运行复制命令前需要添加el.select();

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("value to copy is-->",this.props.copy);
    var copyText = document.getElementById("myInput");

    /* Select the text field */

    copyText.select();

    /* Copy the text inside the text field */
    document.execCommand("copy");
}

关于javascript - 如何将div内容以字符串格式复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56949439/

相关文章:

javascript - 在 JavaScript 中组织扩展方法的最佳实践

javascript - 如何使用 React 和 Babel 从 React-Select CDN 导入?

javascript - 如何使用draft.js插入图像?

reactjs - JEST 测试套件无法运行 : TypeError: (0 , _reactRedux.connect) 不是函数

javascript - Bootstrap slider 冲突

javascript - 在html下拉列表中选择默认值

Javascript 对索引链接数组进行排序

php - 使用客户端空闲计时器的安全性如何/大型网络应用程序开发人员如何做到这一点?

reactjs - 为什么我的 setInterval() 在我的 React 图像 slider 中加速?

javascript - 从具有 2 个属性的异步存储中获取 key