ios下js复制到粘贴板_h5实现一键复制到粘贴板 兼容ios
實現原理
采用document.execCommand('copy')
來實現復制到粘貼板功能
復制必須是選中input框的文字內容,然后執行document.execCommand('copy')
命令實現復制功能。
初步實現方案
const input = document.querySelector('#copy-input');
if (input) {
input.value = text;
if (document.execCommand('copy')) {
input.select();
document.execCommand('copy');
input.blur();
alert('已復制到粘貼板');
}
}
兼容性問題
input 輸入框不能hidden
或者display: none
;
如果需要隱藏輸入框可以使用定位脫離文檔流,然后移除屏幕
#copy-input{
position: absolute;
left: -1000px;
z-index: -1000;
}
2.ios下不能執行document.execCommand('copy')
在 ios 設備下alert(document.execCommand('copy'))
一直返回false
查閱相關資料發現ios下input不支持input.select();
因此拷貝的文字必須存在,不能為空字符串,不然也不會執行復制空字符串的功能
主要是使用textbox.createTextRange
方法選中輸入框的文字
// input自帶的select()方法在蘋果端無法進行選擇,所以需要自己去寫一個類似的方法
// 選擇文本。createTextRange(setSelectionRange)是input方法
function selectText(textbox, startIndex, stopIndex) {
if (textbox.createTextRange) {//ie
const range = textbox.createTextRange();
range.collapse(true);
range.moveStart('character', startIndex);//起始光標
range.moveEnd('character', stopIndex - startIndex);//結束光標
range.select();//不兼容蘋果
} else {//firefox/chrome
textbox.setSelectionRange(startIndex, stopIndex);
textbox.focus();
}
}
3.ios設備上復制會觸發鍵盤彈出事件
給input加上readOnly
只讀屬性
代碼
踩完以上的坑,總結的代碼如下
copyText = (text) => {
// 數字沒有 .length 不能執行selectText 需要轉化成字符串
const textString = text.toString();
let input = document.querySelector('#copy-input');
if (!input) {
input = document.createElement('input');
input.id = "copy-input";
input.readOnly = "readOnly"; // 防止ios聚焦觸發鍵盤事件
input.style.position = "absolute";
input.style.left = "-1000px";
input.style.zIndex = "-1000";
document.body.appendChild(input)
}
input.value = textString;
// ios必須先選中文字且不支持 input.select();
selectText(input, 0, textString.length);
console.log(document.execCommand('copy'), 'execCommand');
if (document.execCommand('copy')) {
document.execCommand('copy');
tools.showTips('已復制到粘貼板');
}
input.blur();
// input自帶的select()方法在蘋果端無法進行選擇,所以需要自己去寫一個類似的方法
// 選擇文本。createTextRange(setSelectionRange)是input方法
function selectText(textbox, startIndex, stopIndex) {
if (textbox.createTextRange) {//ie
const range = textbox.createTextRange();
range.collapse(true);
range.moveStart('character', startIndex);//起始光標
range.moveEnd('character', stopIndex - startIndex);//結束光標
range.select();//不兼容蘋果
} else {//firefox/chrome
textbox.setSelectionRange(startIndex, stopIndex);
textbox.focus();
}
}
};
// 復制文字
// 必須手動觸發 點擊事件或者其他事件,不能直接使用js調用!!!
copyText('h5實現一鍵復制到粘貼板 兼容ios')
總結
以上是生活随笔為你收集整理的ios下js复制到粘贴板_h5实现一键复制到粘贴板 兼容ios的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3种团队分组适应项目_暴利生意:3种适合
- 下一篇: 孔明对张昭的回复有何妙计?