使用原生 JS 复制文本兼容移动端 iOS & android

注意事项

使用 JS 实现复制功能并非很难,可是有几个须要注意的地方。html

首先文本只有选中才能够复制,因此简单的作法就是建立一个隐藏的 input,而后绑定须要复制的文本。浏览器

另外若是将 input 设置为 ``type="hidden"或者display:none则没法选中文本,也就没法复制,能够设置position:absolute;left:-999px;` 来隐藏文本域。app

const copyInput = document.querySelector('#copyInput');
copyInput.value = '须要复制的文本';
copyInput.select();
document.execCommand('Copy');

或者动态建立 inputthis

function copy(str) {
    const input = document.createElement("input");
    input.readOnly = 'readonly';
    input.value = str;
    document.body.appendChild(input);
    input.select();
    input.setSelectionRange(0, input.value.length);
    document.execCommand('Copy');
    document.body.removeChild(input);
}

##移动端禁止键盘弹出spa

在 iOS 中 input 聚焦的时候会弹起键盘,对于复制操做交互体验不好,能够用如下方式禁止键盘的弹起。code

<input type="text" readonly="readonly" />
<input type="text" onfocus="this.blur()" />
$("#box").focus(function(){
    document.activeElement.blur();
});

关于粘贴:除了 IE,现代化的浏览器暂时没法读取剪贴板里的内容。htm

相关文章
相关标签/搜索