JavaScript复制文本到剪切板中

标签:2023-06-29 17:12:33

判断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>
原文出处:http://www.dongblog.com/notes/24.html
来源:博客网 转载请注明出处!

活跃用户

STEP
Ta还没有签名
运行时
Ta还没有签名
"%*[^\n]%*c"
Ta还没有签名
刺客
Ta还没有签名

友情链接


Warning: Smarty error: unable to read resource: "../../../templates/default/./common/foot/footer_index.htm" in /usr/home/hyu3925200001/htdocs/common/smarty/Smarty.class.php on line 1093

Warning: Smarty error: unable to read resource: "../../../templates/default/./common/foot/footer_index.htm" in /usr/home/hyu3925200001/htdocs/common/smarty/Smarty.class.php on line 1093