首页 > 解决方案 > 创建一个按钮来输入文本,保存和复制粘贴到另一个平台

问题描述

我是一名聊天支持人员,具有 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>

标签: javascripthtmlcss

解决方案


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

您的复制功能将如下所示。exceCommand('copy') 函数从 HTML 文档中复制“选择”。因此,首先我们创建一个欺骗 textarea 元素,其中包含您要复制的字符串。然后,我们执行命令将选定的字符串复制到剪贴板。之后,恶搞元素被销毁。此功能还添加 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
      }
    };

推荐阅读