JS复制内容到粘贴板

使用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>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容