javascript - clipboard.js 是如何控制设备的剪切板的?
PHPz
PHPz 2017-04-11 12:58:55
0
1
301

需求大概是:在浏览器中点某个‘复制’按钮之后,写入该按钮的某个属性至剪贴板。
我开始是这样做的:添加一个 input 元素,把它移到用户看不见的位置,把目标字符串写入其中,调用它的 select 方法选中刚输入的内容,然后 document.execCommand('Copy') 来执行复制的操作。

let $copyPlaceholder = $('<input class="copy-placeholder" type="text" />');
$('body').append($copyPlaceholder);

function copyText(text) {
    $copyPlaceholder.val(text);
    $copyPlaceholder[0].select();
    document.execCommand('Copy');
    $copyPlaceholder.val('');
    $copyPlaceholder[0].blur();
    UI.alertSecond('Copied.');
}

这一套在 PC 上是没问题的,但是实测苹果和安卓上的各种浏览器都不支持 document.execCommand,都会返回 false,并且不产生复制的操作。
然后引用了 clipboard.js,手机上也能正常操作了。然而问题来了,我看了半天源码没找到里面的 JS 是怎样和剪贴板交互的,难道除了 document.execCommand() 还有别的路子?

麻烦大家用过这个库的解读一下,非常感谢

PHPz
PHPz

学习是最好的投资!

Antworte allen(1)
迷茫

首先, copy/paste事件必需是用户操作触发, 比如click, touchstart事件等.
其次, iOS上HTMLInputElement#select方法似乎有八阿哥, 得手动调用一下setSelectionRange.

<input id=input/>
<button id=button>Click Me</button>
const input = document.getElementById('input')
const button = document.getElementById('button')
button.addEventListener('click', () => {
    input.focus()
    input.select()
    input.setSelectionRange(0, input.value.length)
    document.execCommand('copy')
})
input.value = '麻烦大家用过这个库的解读一下,非常感谢'

浏览器支不支持可以通过document.queryCommandSupported来检查, 比如:

const supportCopy = !!document.queryCommandSupported && document.queryCommandSupported('copy')
// 在我的iOS模拟器(iPhone 6, iOS 6, 14A345)上`copy`和`paste`都支持, 复制没有问题
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!