日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ios下js复制到粘贴板_h5实现一键复制到粘贴板 兼容ios

發布時間:2025/4/5 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。