javascript - 创建一个按钮来输入文本,保存并复制以粘贴到另一个平台

标签 javascript html css

我是一名聊天支持人员,拥有 HTML5/CSS3 知识和一点 JS。 我想要一个代码,在其中我可以在单个按钮上输入一个脚本。 例如,“我能为您提供什么帮助?”或“感谢您联系我们” 该按钮存储并复制脚本,因此我可以在单击它时将其粘贴为回复。 这样,我可以根据查询类别轻松地从多个按钮中进行选择。 我可以节省输入冗长的愚蠢重复问题回复的时间。

这是我所做的一个例子,

<td colspan="1"><div id = "chat">
<button onclick="copy('Are you still there?')">Still there?</button>
<button onclick="copy('One moment please')">1moment</button></div>

最佳答案

我也不知道这个,但是根据 Hacker Noon

你的复制函数看起来像这样。 exceCommand('copy') 函数从 HTML 文档复制“选择”。因此,首先我们创建一个欺骗性的文本区域元素,其中包含您要在其中复制的字符串。然后,我们执行将所选字符串复制到剪贴板的命令。之后,欺骗元素被销毁。此函数还添加了 CSS 属性以确保用户视觉不受影响。

  const copy = str => {
      const el = document.createElement('textarea');  // Create a <textarea> element
      el.value = str;                                 // Set its value to the string that you want copied
      el.setAttribute('readonly', '');                // Make it readonly to be tamper-proof
      el.style.position = 'absolute';                 
      el.style.left = '-9999px';                      // Move outside the screen to make it invisible
      document.body.appendChild(el);                  // Append the <textarea> element to the HTML document
      const selected =            
        document.getSelection().rangeCount > 0        // Check if there is any content selected previously
          ? document.getSelection().getRangeAt(0)     // Store selection if found
          : false;                                    // Mark as false to know no selection existed before
      el.select();                                    // Select the <textarea> content
      document.execCommand('copy');                   // Copy - only works as a result of a user action (e.g. click events)
      document.body.removeChild(el);                  // Remove the <textarea> element
      if (selected) {                                 // If a selection existed before copying
        document.getSelection().removeAllRanges();    // Unselect everything on the HTML document
        document.getSelection().addRange(selected);   // Restore the original selection
      }
    };

关于javascript - 创建一个按钮来输入文本,保存并复制以粘贴到另一个平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603327/

相关文章:

javascript - 应用内浏览器不会关闭

php - 为标签命名并调用 if isset 函数

javascript - 在不删除关联事件的情况下从节点中删除元素?

css - 在 CSS 中组合 :last-child with :not(. 类)选择器

javascript - [ karma ] : Error: Unable to resolve module [expose-loader? jQuery!jquery]

javascript - 使用 TAB 防止循环浏览页面元素

javascript - 如何在switch语句中添加执行自定义函数

javascript - 根据其背后的图像更改标题颜色

html - 如何设置html和body标签包裹全屏?

jquery - 带有jquery的可点击菜单