Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Js 复制到粘贴板 #56

Open
susouth opened this issue Dec 9, 2019 · 0 comments
Open

Js 复制到粘贴板 #56

susouth opened this issue Dec 9, 2019 · 0 comments
Labels
JavaScript 跟js相关的面试题 No.56

Comments

@susouth
Copy link
Contributor

susouth commented Dec 9, 2019

📚在线阅读:Js 复制到粘贴板 - No.56

这是一个简单的小知识,本周我做了一个简单的“复制到剪贴板”按钮,这是我第一次做这种功能,向大家分享一下我的实现方法。

这很简单,比较麻烦的是我们必须为需要复制的文本增加<input/>标签。之后我们选择要复制的内容然后调用复制命令execCommand.
execCommand('copy') 将会复制被选择的内容。

此方法目前被所有最新版本的浏览器支持,它可以让我们执行如复制剪切粘贴等命令,还可以改变字体颜色、大小等。

document.querySelector('#input').select();
document.execCommand('copy');

具体表现看这里

方法二:

借助 clipboard.js
直接引用: <\script src="dist/clipboard.min.js"></script>
包: npm install clipboard --save ,然后 import Clipboard from 'clipboard';

// 复制成功后执行的回调函数
clipboard.on('success', function(e) {
    console.info('Action:', e.action); // 动作名称,比如:Action: copy
    console.info('Text:', e.text); // 内容,比如:Text:hello word
    console.info('Trigger:', e.trigger); // 触发元素:比如:<button class="btn" :data-clipboard-text="copyValue">点我复制</button>
    e.clearSelection(); // 清除选中内容
});

// 复制失败后执行的回调函数
clipboard.on('error', function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
});

扩展阅读:

@susouth susouth added JavaScript 跟js相关的面试题 No.56 labels Dec 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 跟js相关的面试题 No.56
Projects
None yet
Development

No branches or pull requests

1 participant