通过查阅资料了解到可以通过document.execCommand('copy')实现复制功能,然而该功能不支持ios 10以下的版本,且该功能存在如下限制:
- 只能复制
input和textarea里的内容 - 被复制的元素不能设置样式为
display: none或visibility: hidden - 被复制的内容必须是选中的
功能实现
步骤:找到目标 > 选中文本 > 复制
- 通常我们需要复制的文本并不是放在
input或者textarea中,我们可以预先写一个备用的input在文档中。由于选中文本时ios会高亮选中的区块,即使将样式设置为opacity: 0,高亮依然存在,所以我们需要将这个input移到视口之外。如:
<input
id="copyInput"
type="text"
value="123456"
style="position: fixed;top: -100px;left: 0">
- 我们可以通过
input.select()方法选中元素,通过测试发现安卓中表现很不错,然而ios中并不生效。在此我们借用 range 来实现ios下的选中效果,然后选中想要复制的文本。 - 执行复制及后续处理。
完整代码如下:
funCopy() {
let input = document.querySelector('#copyInput');
input.focus();
input.select();
if(/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
let range = document.createRange();
range.selectNodeContents(input);
let sel = window.getSelection()
sel.removeAllRanges();
sel.addRange(range);
}
input.setSelectionRange(0, 9999); // 给一个较大的数字确保完全覆盖input的内容
let copyStatus = document.execCommand('copy');
input.blur()
if(copyStatus) {
// 复制成功
} else {
// 复制失败
}
}
该方案在ios中表现并不完美,以下:
- ios中由于
input有个获取焦点的过程,会导致键盘闪现 - ios 11及以下会导致页面向
input所在的方向滚动。(本例中会向上滚动)