只若初见

js实现复制文本

电脑版发表于:2020/5/20 22:37

方法一:

function copyContent(content) {
        //获取要赋值的input的元素
        var inputElement = document.getElementById("copy_content");
        //给input框赋值
        inputElement.value = content;
        //选中input框的内容
        inputElement.select();
        // 执行浏览器复制命令
        document.execCommand("Copy");
        //提示已复制
        alert('已复制');
    }

这种方式只能复制,text,textarea的内容,而且!!!不能 复制隐藏域的内容


方法二:借助第三方Js之clipboard.js

下载地址:

使用:

var clipboard = new ClipboardJS('#mytestbut', {
            text: function () {
                return $("#copy_content").val();
            }
        });

        clipboard.on('success', function (e) {
            alert('已复制')

            e.clearSelection();
        });

        clipboard.on('error', function (e) {
            alert("复制失败");
        });

这里的mytestbut就是你按钮的id,当然可以是class选择器,然后copy_content就是你需要复制的内容比如text,textare而且可以是隐藏域!

注意那个text哪里不能直接复制,他就是设计的通过一个回调函数来!




关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢