通过 input 实现 js 的复制功能,注意文本只有选中才可以复制。disabled 禁止输入不能获取焦点,不可以复制。readonly 只读属性能获取焦点,可以复制。
有input时,实现的代码:
<input id="copyInput" type="text" οnclick="copy" value="复制的内容" readonly="readonly">
function copy() {
const copyInput = document.querySelector('#copyInput');
// copyInput.readOnly = 'readonly';
// copyInput.value = '需要复制的文本';
copyInput.select(); // select text
copyInput.setSelectionRange(0, input.value.length);
document.execCommand('Copy');
}
无input时,实现的代码:
function copy(str) {
const copyInput = document.createElement("input");
copyInput.readOnly = 'readonly';
copyInput.value = str;
document.body.appendChild(copyInput);
copyInput.select(); // select text
copyInput.setSelectionRange(0, input.value.length);
document.execCommand('Copy');
copyInput.remove()
// document.body.removeChild(copyInput);
}
移动端禁止键盘弹起
以下两方法,亲测发现iOS键盘内容没有弹出来,键盘头部还是出来的,android的没有。
<input type="text" readonly="readonly" />
<input type="text" onfocus="this.blur()" />