更新!IOS>=10
Looks like with the help of selection ranges and some little hack it is possible to directly copy to the clipboard on iOS (>= 10) Safari. I personally tested this on iPhone 5C iOS 10.3.3 and iPhone 8 iOS 11.1. However, there seem to be some restrictions, which are:
- 只能从
<input>
和<textarea>
元素复制文本.
- 如果包含文本的元素在
<form>
内是not,则它必须是contenteditable
.
- 包含文本的元素必须是not是
readonly
(尽管您可以try ,但这不是任何地方记录的"官方"方法).
- 元素内的文本必须在 Select 范围内.
要满足这四个"要求",您必须:
- 将要复制的文本放入
<input>
或<textarea>
元素中.
- 保存元素的旧值
contenteditable
和readonly
,以便能够在复制后恢复它们.
- 将
contenteditable
改为true
,将readonly
改为false
.
- 创建一个range以 Select 所需的元素,并将其添加到窗口的 Select 中.
- 为整个元素设置selection range.
- 恢复之前的
contenteditable
和readonly
值.
- 跑
execCommand('copy')
英里.
这将导致用户设备的插入符号移动并 Select 所需元素中的所有文本,然后自动发出复制命令.用户将看到选中的文本,并显示带有 Select /复制/粘贴选项的工具提示.
Now, this looks a little bit complicated and too much of an hassle to just issue a copy command, so I'm not sure this was an intended design choice by Apple, but who knows... in the mean time, this currently works on iOS >= 10.
也就是说,可以使用像this one这样的多边形填充来简化此操作,并使其跨浏览器兼容(感谢@Toskan在注释中提供链接).
Working example个
总而言之,您需要的代码如下所示:
function iosCopyToClipboard(el) {
var oldContentEditable = el.contentEditable,
oldReadOnly = el.readOnly,
range = document.createRange();
el.contentEditable = true;
el.readOnly = false;
range.selectNodeContents(el);
var s = window.getSelection();
s.removeAllRanges();
s.addRange(range);
el.setSelectionRange(0, 999999); // A big number, to cover anything that could be inside the element.
el.contentEditable = oldContentEditable;
el.readOnly = oldReadOnly;
document.execCommand('copy');
}
请注意,此函数的el
参数必须是<input>
或<textarea>
.
旧答案:以前的iOS版本
在iOS < 10上,Safari(实际上是安全措施)对Clipboard API有一些限制:
- 它仅在有效 Select 上激发
copy
个事件,仅在聚焦的可编辑字段中激发cut
和paste
个事件.
- It only supports OS clipboard reading/writing via shortcut keys, not through 100.请注意,"shorcut键"是指一些可点击的键(例如复制/粘贴操作菜单或自定义iOS键盘快捷键)或物理键(例如连接的蓝牙键盘).
- 它不支持
ClipboardEvent
构造函数.
所以(至少到目前为止)it's not possible to programmatically copy some text/value in the clipboard on an iOS device using Javascript个.只有用户可以决定是否复制某些内容.
It is however possible to select something programmatically,这样用户只需点击选项上显示的"复制"工具提示.这可以通过与上面完全相同的代码来实现,只需删除execCommand('copy')
,这确实是行不通的.