js 复制文本到剪贴版

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/oYuLian/article/details/84629171

1.纯js

<body>
   <!--input 不能有disable 样式不能有font-size:0, height和width也要正常 display不能为none-->
  <input style="opacity" id="getRedinput" value="被复制的内容"/>
  <script>
       /*注意 只能由用户手动点击才能复制,js模拟点击无效*/
       function copy(){
            var getRedinput = document.getElementById("getRedinput");
            const valueLength = getRedinput.value.length;
            getRedinput.focus();
            getRedinput.setSelectionRange(0, valueLength);
            document.execCommand("copy");
            getRedinput.blur();
       }
  </script>
</body>

2.第三方库clipboard

 https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js   
<div id="target">
        复制的内容
   </div>
   <button class="btn" type="button" onclick="hcopy()" data-clipboard-action="copy" data-clipboard-target="#target" id="copy_btn">复制链接</button>

    function hcopy() {
            var clipboard = new Clipboard('#copy_btn');
     
            clipboard.on('success', function (e) {
                e.clearSelection();
               
            });
            clipboard.on('error', function (e) {
           
               
            });
        }

注意:要使用button标签,并且要用户主动点击才行。

3.适用于ios的

var btn = document.querySelector('body');
        btn.addEventListener('click', function(){
            var input = document.createElement('input');
            input.setAttribute('readonly', 'readonly');
            input.setAttribute('value', "复制的内容");
            document.body.appendChild(input);
            input.setSelectionRange(0, 9999);
            if (document.execCommand('copy')) {
                document.execCommand('copy');
            }
            document.body.removeChild(input);
        })

4.三端通用

   var getTextHtml='<div style="opacity:0;position:relative;top:-10000px;" id="getADTXT">'+被复制的内容+'</div>';
        document.body.insertAdjacentHTML("beforeend", getTextHtml);         
  var range = document.createRange();
            var tar = document.querySelector('#getADTXT');
            range.selectNodeContents(tar);
            var selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
            document.execCommand('copy');
            selection.removeAllRanges();

猜你喜欢

转载自blog.csdn.net/oYuLian/article/details/84629171