2023年11月25日发(作者:)
h5实现⼀键复制到粘贴板兼容iOS
效果展⽰
实现原理
采⽤ mmand('copy') 来实现复制到粘贴板功能
复制必须是选中input框的⽂字内容,然后执⾏mmand('copy')命令实现复制功能。
初步实现⽅案(⾮完整代码):
// 此代码 在iOS下有bug,完整代码在最后贴出
const input = elector('#copy-input');
if (input) {
= text;
if (mmand('copy')) {
();
mmand('copy');
();
alert('已复制到粘贴板');
}
}
兼容性问题
1、input 输⼊框不能 hidden 或者 display: none;
如果需要隐藏输⼊框可以使⽤定位脱离⽂档流,然后移除屏幕
#copy-input{
position: absolute;
left: -1000px;
设备上复制会触发键盘弹出事件
给 input 加上 readOnly 只读属性。
代码
踩完以上的坑,总结的代码如下
copyText (text) {
// 数字没有 .length 不能执⾏selectText 需要转化成字符串
const textString = ng();
let input = elector('#copy-input');
if (!input) {
input = Element('input');
= "copy-input";
ly = "readOnly"; // 防⽌ios聚焦触发键盘事件
on = "absolute";
= "-1000px";
= "-1000";
Child(input)
}
= textString;
// ios必须先选中⽂字且不⽀持 ();
selectText(input, 0, );
(mmand('copy'), 'execCommand');
if (mmand('copy')) {
mmand('copy');
alert('已复制到粘贴板');
}
();
// input⾃带的select()⽅法在苹果端⽆法进⾏选择,所以需要⾃⼰去写⼀个类似的⽅法
// 选择⽂本。createTextRange(setSelectionRange)是input⽅法
function selectText(textbox, startIndex, stopIndex) {
if (TextRange) {//ie
const range = TextRange();
se(true);
art('character', startIndex);//起始光标
d('character', stopIndex - startIndex);//结束光标
();//不兼容苹果
} else {//firefox/chrome
ectionRange(startIndex, stopIndex);
();
}
}
};
发布评论