4

js点击一键复制文本功能(clipboard)

 2 years ago
source link: https://www.geekjc.com/post/5f413ffc9713216ccd00c1d5
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

js点击一键复制文本功能(clipboard)

时间: 08/22/2020作者: ll浏览量: 1495

有时候我们遇到需求是,点击按钮复制文本,方便用户直接复制粘贴所需要的内容,这个功能很多网站或者应用都是有的功能。怎么实现呢?

1. 原生实现

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

/**
 * 一键粘贴
 * @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);
    }
}

2. clipboard.js实现

clipboard.js 是一个不需要flash,将文本复制到剪贴板的插件。

2.1 基本使用

首先需要您需要通过传递DOM选择器,HTML元素或HTML元素列表来实例化它。

<pre>  
new Clipboard('.btn');  
</pre>

1用一个元素当触发器来复制另一个元素的文本,data-clipboard-target属性后需要跟属性选择器

<pre>  

<input id="foo" value="https://github.com/zenorocha/clipboard.js.git">


<button class="btn" data\-clipboard\-target="#foo">  
</button>  
</pre>

另外还有另外一个属性data-clipboard-action属性,以指定是要要么copy还是要cut操作。默认情况下是copy。cut操作只适用于<input><textarea>元素。

<pre>  

<textarea id="bar">Mussum ipsum cacilds...</textarea>


<button class="btn" data\-clipboard\-action="cut" data\-clipboard\-target="#bar">  
Cut to clipboard  
</button>  
</pre>

2从属性中复制文本,不需要另一个元素当触发器,可以使用data-clipboard-text属性,在后面放上需要复制的文本.

<pre>  
<button class="btn" data\-clipboard\-text="Just because you can doesn't mean you should — clipboard.js">  
Copy to clipboard  
</button>  
</pre>

3. 更多相关文章

关注下面的标签,发现更多相似的文章

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK