企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 前言 今天来谈谈一个小小的需求: 产品:说给我这个添加一个复制功能,点一下把内容给我复制到粘贴板上。 我:好嘞 我:说上就上,5分钟搞定,部署上去看一下,美滋滋,又是一天 5分钟过去了... 测试:测试通过,可以了 产品:复制提示成功了,但是没有在粘贴板上呢!!! 我和测试:蒙蔽了,咋会呢 产品:我的是苹果电脑 我和测试:靠,产品这么豪吗?都没想BUG,一心想着,自己那破电脑... 我:没办法了,只能看一下什么问题了... 我:又是5分钟过去了,发现:input自带的select()方法在苹果端无法进行选择,问题找出了,那就干吧。 ... ### 先看看我5分钟CV出来的代码 ``` js // 点击复制到剪贴板函数 copyToClipboard(content) {       if (window.clipboardData) {         window.clipboardData.setData('text', content)       } else {         (function(content) {           document.oncopy = function(e) {             e.clipboardData.setData('text', content)             e.preventDefault()             document.oncopy = null           }         })(content)         document.execCommand('Copy') } ``` * 注:ios下不能执行document.execCommand('copy') 在ios设备下`alert(document.execCommand('copy'))`一直返回`false` 查阅相关资料发现ios下input不支持`input.select();` * 其他兼容问题: input 输入框不能`hidden`或者`display: none`; 如果需要隐藏输入框可以使用定位脱离文档流,然后移除屏幕 ### 解决input自带的select()方法在苹果端无法进行选择 直接上完整代码,看着就比较简单了 ``` js copyText(text) {       const textString = text.toString() // 数字没有 .length 不能执行selectText 需要转化成字符串       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 = '-2000px'         input.style.zIndex = '-2000'         document.body.appendChild(input)       }       input.value = textString       // ios必须先选中文字且不支持 input.select();       this.selectText(input, 0, textString.length)       if (document.execCommand('copy')) {         document.execCommand('copy')         this.$message.success('复制成功!')       } else {         this.$message.success('复制失败!')       }       input.blur() } ``` ### input自带的select()方法在苹果端无法进行选择,所以需要自己去写一个类似的方法 ``` js // 选择文本。createTextRange(setSelectionRange)是input方法 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') * 移动端: 安卓手机:微信(chrome)和几个手机浏览器都可以用; 苹果手机:微信里面和sarafi浏览器里也都可以; * PC: sarafi版本必须在10.2以上,其他浏览器可以。 ## 总结 1.坑都是一步步填过来的,不要把没做过作为理由,犯了就改,这就是经验了,虽然表面上不是什么大问题,但是小心总是好的; 2.做事情需要考虑全面,不要让“所谓得小事”而不放在心上,小事如果多了,性质就不一样了 3.做事谨慎、谨慎、谨慎,重要得事情要说三次。