粘贴复制

一曲冷凌霜 提交于 2020-01-06 16:14:36

js实现粘贴到剪贴板的功能

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>copy example</title>
</head>
<body>

<input type="text" placeholder="请输入文字" id="selector">
<button id="copy">点击复制</button>
</body>


<script>
    var copy = document.querySelector('#copy')
    copy.addEventListener('click',()=>{
        var val = document.querySelector("#selector");
        val.select()
        document.execCommand('Copy')
    },false)
</script>
</html>

第二个

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>copy example</title>
</head>
<body>

<a id="selector">我是老大</a>
<button id="copy">点击复制</button>

  
</body>


<script>
var aEle = document.querySelector('#copy');
    aEle.addEventListener('click',function(){
        var copyDOM = document.querySelector('#selector');  
        var range = document.createRange();  
        range.selectNode(copyDOM);
        window.getSelection().addRange(range);
        var successful = document.execCommand('copy');  
        try{  
            var msg = successful ? 'successful' : 'unsuccessful';  
            console.log('Copy email command was ' + msg);  
        }catch(err) {  
            console.log('Oops, unable to copy');  
        }
        window.getSelection().removeAllRanges();  
    },false);
    
</script>
</html>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!