button class="btn" data-clipboard-text="123456"
click to copy
button
new Clipboard('.btn');
$('.btn').trigger('click');
// nothing to happen
应该是浏览器的安全限制,要有一个event才执行剪切板的相关操作,这里的event需要注意,用js代码创建的event 和 用户交互式(即用户正常鼠标点击)产生的event有一定的区别的。比如,
This is the browser's security limit,we need a truth event to operate clipborad,it is a different obj from event which created by your program(like js code),such as:
domXxx.click(); // domXxx.onClick();
$('.xx').click(); // $('.xx').trigger('click');
等,都是不会让copy效果生效的,clipboard.js 会抛error
It unwork and you will catch a error.
这里有说明的
See the detail in this link.
wiki/Known-Limitations
重点:有一种曲线救国的方式:
function clipboard(text, event) {
const cb = new Clipboard('.null', {
text: () => text
});
cb.on('success', function(e) {
console.log(e);
cb.off('error');
cb.off('success');
});
cb.on('error', function(e) {
console.log(e);
cb.off('error');
cb.off('success');
});
cb.onClick(event);
}
用法:
let domNode = document.getElementById('yourBtn');
domNode.addEventListener('click', event => clipboard('some text you need copy', event));