使用js一建复制文字

整体思路

  • 定义要复制的文字
  • 选中要复制的文字(一键复制一般为全选)
  • 复制文字

按照上方的思路,还可以分成下面两种情况

一、复制 input 标签内的文本

html文件 这里我使用了element-ui组件

 <el-form-item label="代理分享链接:" class="copy">
          <span id="copytext">www.baidu.com</span>
          <input type="text" id="input" value="www.baidu.com"/>
          <el-button type="primary" @click="copytext"> 复制 </el-button>
</el-form-item>

要复制的文字为input标签中的value,也就是百度链接
JavaScript文件 点击 复制 按钮后的操作

   copytext() {
      var input = document.getElementById("input");
      console.log(input.value);
      input.select(); // 选中文本
      document.execCommand("copy");  //复制文本
      if (input.value) {
        this.$message({
          message: "复制成功",
          type: "success",
        });
      }else{
        this.$message({
          message: "没有可选中的链接",
          type: "warning",
        });
      }
    },

二、复制 span、div、p 标签内的文本

复制span、div、p标签内的文本和上面有些许不同

原因:如果是输入框,可以通过 select()方法,选中输入框的文本,然后调用 copy 命令,将文本复制到剪切板

但是 select()方法只对 <input><textarea>有效,对于<span>等就不好用。

所以我的解决方案是,在页面中添加一个 <input>标签,然后把它隐藏掉
点击按钮的时候,先把 <input>的 value 改为 <span>innerText,然后复制 <input> 中的内容

html文件

 <el-form-item label="代理分享链接:" class="copy">
          <span id="copytext">www.baidu.com</span>
          <el-button type="primary" @click="copytext"> 复制 </el-button>
          <input type="text" id="input" />
        </el-form-item>

JavaScript文件

    copytext() {
      //获取文本内容
      var text = document.getElementById("copytext").innerText;  
      console.log(text);
      var input = document.getElementById("input");
      input.value = text; // 修改文本框的内容
      console.log(input.value);
      input.select(); // 选中文本

      document.execCommand("copy");   //复制文本
      if (input.value) {
        this.$message({
          message: "复制成功",
          type: "success",
        });
      }else{
        this.$message({
          message: "没有可选中的链接",
          type: "warning",
        });
      }
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容