好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

JS实现一键复制

原生js实现点击按钮复制文本,供大家参考,具体内容如下

最近遇到一个需求,需要点击按钮,复制 聊天记录的文本到剪切板

一、原理分析

浏览器提供了 copy 命令 ,可以复制选中的内容

document.execCommand("copy")

如果是输入框,可以通过 select() 方法,选中输入框的文本,然后调用 copy 命令,将文本复制到剪切板

但是 select() 方法只对 和 有效,对于就不好使

最后我的解决方案是,在页面中添加一个 ,然后把它隐藏掉点击按钮的时候,先把 的 value 改为的 innerText,然后复制 中的内容

二、代码实现

<style type="text/css">
? ?.wrapper {position: relative;}
? ?#input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;}
</style>

<div class="wrapper">
? ?<p id="text">我把你当兄弟你却想着复制我?</p>
? ?<textarea id="input">这是幕后黑手</textarea>
? ?<button onclick="copyText()">copy</button>
</div>

<script type="text/javascript">
? ? function copyText() {
? ? ? var text = document.getElementById("text").innerText;
? ? ? var input = document.getElementById("input");
? ? ? input.value = text; // 修改文本框的内容
? ? ? input.select(); // 选中文本
? ? ? document.execCommand("copy"); // 执行浏览器复制命令
? ? ? alert("复制成功");
? ? }
? ? //或者
? ? function copyText(value) {
? ? ? ? // 创建元素用于复制
? ? ? ? var aux = document.createElement("input");

? ? ? ? // 设置元素内容
? ? ? ? aux.setAttribute("value", value);

? ? ? ? // 将元素插入页面进行调用
? ? ? ? document.body.appendChild(aux);

? ? ? ? // 复制内容
? ? ? ? aux.select();

? ? ? ? // 将内容复制到剪贴板
? ? ? ? document.execCommand("copy");

? ? ? ? // 删除创建元素
? ? ? ? document.body.removeChild(aux);

? ? ? ? //提示
? ? ? ? alert("复制内容成功:" + aux.value);
? ? }
? </script>

三、一键复制

分享一个自己工作中用到的一键复制方法

/**
?* 一键粘贴
?* @param ?{String} id [需要粘贴的内容]
?* @param ?{String} attr [需要 copy 的属性,默认是 innerText,主要用途例如赋值 a 标签上的 href 链接]
?*
?* range + selection
?*
?* 1.创建一个 range
?* 2.把内容放入 range
?* 3.把 range 放入 selection
?*
?* 注意:参数 attr 不能是自定义属性
?* 注意:对于 user-select: none 的元素无效
?* 注意:当 id 为 false 且 attr 不会空,会直接复制 attr 的内容
?*/
copy (id, attr) {
? ? let target = null;

? ? if (attr) {
? ? ? ? target = document.createElement('div');
? ? ? ? target.id = 'tempTarget';
? ? ? ? target.style.opacity = '0';
? ? ? ? if (id) {
? ? ? ? ? ? let curNode = document.querySelector('#' + id);
? ? ? ? ? ? target.innerText = curNode[attr];
? ? ? ? } else {
? ? ? ? ? ? target.innerText = attr;
? ? ? ? }
? ? ? ? document.body.appendChild(target);
? ? } else {
? ? ? ? target = document.querySelector('#' + id);
? ? }

? ? try {
? ? ? ? let range = document.createRange();
? ? ? ? range.selectNode(target);
? ? ? ? window.getSelection().removeAllRanges();
? ? ? ? window.getSelection().addRange(range);
? ? ? ? document.execCommand('copy');
? ? ? ? window.getSelection().removeAllRanges();
? ? ? ? console.log('复制成功')
? ? } catch (e) {
? ? ? ? console.log('复制失败')
? ? }

? ? if (attr) {
? ? ? ? // remove temp target
? ? ? ? target.parentElement.removeChild(target);
? ? }
}

实现效果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于JS实现一键复制的详细内容...

  阅读:57次