手写常用js工具函数--剪切内容

手写常用js工具函数–剪切内容

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>简易剪贴板</title>
</head>

<body>
  <button id="btn">点击复制</button>
  <script>
    let btn = document.getElementById('btn')
    // 监听按钮点击事件
    btn.addEventListener('click',copyValue,true)
    function copyValue(){
      //  创建input并设置相应的样式  隐藏
      let targetInput = document.createElement('input')
      targetInput.style.position = 'absolute'
      targetInput.style.left = '-99999px'
      targetInput.style.top = '-99999px'
      targetInput.id = 'test'
      targetInput.value = btn.innerHTML
      document.body.appendChild(targetInput)  
      document.getElementById('test').addEventListener('copy',getTargetValue,true)
      document.getElementById('test').select()
      document.execCommand('copy',true)
      // 把之前的清除
      if(document.getElementById('test')){
        let box = document.getElementById('test')
        box.parentNode.removeChild(box)
      }
       
      function getTargetValue(e){
        if(isIE()){
          if(window.clipboardData){
             window.clipboardData.setData('Text',e.target.value)
          }
        }else{
          e.preventDefault()
          if(e.clipboardData){
            e.clipboardData.setData('text/plain',e.target.value)
          }
        }
      }
    }
    // 判断是否IE浏览器
    function isIE () {
      var input = window.document.createElement('input')
      if (window.ActiveXObject === undefined) return null
      if (!window.XMLHttpRequest) return 6
      if (!window.document.querySelector) return 7
      if (!window.document.addEventListener) return 8
      if (!window.atob) return 9
      if (!input.dataset) return 10; return 11
    }
    
  </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值