使用JS实现点击复制文本

5,525 阅读1分钟

点击按钮实现复制文本内容功能

<input class="layui-input" id="copyvalue">
    <button type='button' class='layui-btn' onclick=copyfun>点击复制</button>
    //复制input框的内容
    function copyfun(){
      var e = document.getElementById("copyvalue");
      e.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      alert("复制成功");
    }

进阶:不依靠输入框输入,隐藏input,点击复制自定义的内容

注意:这里input 不能hidden,也不能 display: none,否则复制不成功

<input class="layui-input" id="copyvalue" style="opacity: 0;position: absolute;">
    <button type='button' class='layui-btn' onclick=copyfun>点击复制</button>
    //复制input框的内容
    function copyfun(){
      let text='要赋值的内容'
      $('#copyvalue').val(text)
      var e = document.getElementById("copyvalue");
      e.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      alert("复制成功");
    }

改进方法
这样可以不用在html里写 input,灵感来源于 创建 a 标签下载链接

 function copyfun(){
 	  var copyipt = document.createElement("input");
      var text = "需要复制的内容";
      copyipt.setAttribute("value", text);
      document.body.appendChild(copyipt);
      copyipt.select();
      document.execCommand("copy");
	  document.body.removeChild(copyipt);
}