美文网首页
JS复制内容到粘贴板

JS复制内容到粘贴板

作者: 遇见I你 | 来源:发表于2020-05-12 17:00 被阅读0次

使用document.execCommand()方法 - 复制内容到粘贴板

which allows one to run commands to manipulate the contents of the editable region.

//可以允许运行命令来操作可编辑区域的内容。(注意:是可编辑区域)

定义:

var bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

aCommandName :表示命令名称,如: copy, cut 等;

aShowDefaultUI:是否展示用户界面,一般情况下都是 false;

aValueArgument:有些命令需要额外的参数,一般用不到;

兼容性:

这个方法在之前的兼容性其实是不太好的,但是好在现在已经基本兼容所有主流浏览器了,在移动端也可以使用。

使用:

<div id="app">

        <span class="order-copy" @click='btnclick'></span>    

</div>

<script type="text/javascript">

    var vm = new Vue() {

        el: '#app',

        data: {},

        methods: {

                function clipboard(string) { 

                        const input = document.createElement('input');

                        document.body.appendChild(input);                        

                        input.setAttribute('readonly', 'readonly');

                        input.setAttribute('value', string); 

                        input.setSelectionRange(0, 99999);

                         if (document.execCommand('copy')) {

                                document.execCommand('copy');

                                //复制成功

                         }

                         document.body.removeChild(input);

                },

                btnclick()  {

                    string = ''复制内容到粘贴板'';

                    clipboard(string);

                }

          }

    }

</script>

相关文章

网友评论

      本文标题:JS复制内容到粘贴板

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