美文网首页
document.execCommand实现复制文本的功能

document.execCommand实现复制文本的功能

作者: 优秀的收藏转载分享 | 来源:发表于2021-06-21 14:18 被阅读0次
<!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>Document</title>
</head>
<body>

  <div style="margin-top:50px;">
    <!-- <input id='copyText'  value="我是要模拟复制的内容" style='opacity: 0;position: absolute;' type="text">
    <input value="我是要模拟复制的内容" disabled type="text"> -->

    <input id="copyText" type="text" value="我是要模拟复制的内容">
    <button class="btnText">copy</button>
  </div>

</body>
<script>
  function copyTextarea(id) {
     let target = null
     target = document.querySelector('#' + id)
     target.select()
     let copyResult = document.execCommand('copy')
     window.getSelection().removeAllRanges()
     if (copyResult) {
       console.log('复制成功')
     } else {
       console.log('复制失败')
     }
   }

   let btnText = document.querySelector('.btnText')
   btnText.addEventListener('click', (e) => {
     copyTextarea('copyText')
   })
</script>
</html>

不能复制成功的原因:

1、input框不能有disabled属性;
2、根据第一条扩展,input的width || height 不能为0;
3、input框不能有hidden属性;
4、ID名称要唯一;

相关文章

网友评论

      本文标题:document.execCommand实现复制文本的功能

      本文链接:https://www.haomeiwen.com/subject/nosyyltx.html