JS点击复制文本

创建文本域,通过文本域复制内容。选中文本域后复制,之后删除文本域。实现复制。

HTML

创建文本域,通过文本域复制内容。选中文本域后复制,之后删除文本域。实现复制;

<button class="copy" onclick="copy()">复制</button>
<div class="copy_con">需要复制的内容</div>

JQ

    function copy() {
        var textarea = document.createElement("textarea");
        // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
        textarea.readOnly = 'readonly';
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        // 将要 copy 的值赋给 textarea 标签的 value 属性
        textarea.value = document.getElementsByClassName('copy_con')[0].innerText;
        // 将 textarea 插入到 body 中
        document.body.appendChild(textarea);
        // 选中值并复制
        textarea.select();
        textarea.setSelectionRange(0, textarea.value.length);
        document.execCommand("Copy");
        document.body.removeChild(textarea);
        console.log("复制成功");
    };
Licensed under 京ICP备17003353号-3