前端实现复制的功能

第一种情况:

点击复制按钮,实现文本的复制或者其他内容的复制,下边我是将复制的内容当成了参数,进行的操作。

<button @click="copy('这是一段内容')" >复制</button>

// 复制的方法

copy (value) {

        //创建input标签

        var input = document.createElement('input')

        //将input的值设置为需要复制的内容

        input.value = value;

        //添加input标签

        document.body.appendChild(input)

        //选中input标签

        input.select()

        //执行复制

        document.execCommand('copy')

        //成功提示信息

        this.$message.success('复制成功!')

        //移除input标签

        document.body.removeChild(input)

},

第二种情况:

点击复制按钮,实现复制input框的内容

<template>
        <div id="app">
                请输入你需要复制的内容:<input id="copy" v-model="message"/>
                <button v-on:click="copy()">复制</button>
        </div>
</template>

<script>
export default {
        name: 'App',
        data() {
                return {
                        message: ''
                }

        },
        methods: {
                copy () {
                        //获取input对象
                        var input = document.getElementById('copy')
                        //选中input标签
                        input.select()
                        //执行复制
                        document.execCommand('copy')
                        this.$message.success('复制成功!')
                },
        },
}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_50999303/article/details/130942617