博主:DongJiang
码龄:7年
等级:
文章:631
访问:52336
博客简介:DongJiang的博客
博客创建时间:2018-04-12
给博主送颗小红心
1002
后台管理系统: 进入后台

JavaScript复制文本到剪切板中

判断navigator.clipboard是否为undefined,因为navigator.clipboard对象只能在安全网络环境中才能使用,比如在localhost或者https中才能正常使用,直接用ip地址和http访问出现undefined,所以需要表单元素来实现。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="copy">复制</button>
    <div id="text">你好啊</div>
    <script>
      var copy = document.getElementById('copy')
      copy.onclick = function copy(e) {
        var text = document.getElementById('text')
        if (navigator.clipboard && window.isSecureContext) {
          return navigator.clipboard.writeText(text.innerHTML)
        } else {
          let input = document.createElement('input')
          document.body.appendChild(input)
          input.value = text.innerHTML
          input.focus()
          input.select()
          if (document.execCommand('copy')) {
            document.execCommand('copy')
          }
          input.blur()
          document.body.removeChild(input)
        }
      }
    </script>
  </body>
</html>
原文出处:
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。