简介
当文档对象被转换为设计模式的时候(选中,设置contentEditable等),文档对象提供了一个execCommand方法,通过给这这个方法传递参数命令可以操作可编辑区域的内容。这个方法的命令大多数是对文档选中区域的操作
(如bold, italics等), 也可以插入一个元素(如增加一个a链接) 或者修改一个完整行 (如缩进).。当元素被设置了contentEditable,通过执行execCommand
方法可以对当前活动元素进行很多操作。
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
执行以下解决方案条件:(这个是原理)
①执行复制方法时 所复制文字不能被任何 块级元素和行内块元素和行内元素遮盖否则无效;(解决方案:将文本通过绝对定位或其他方式移除屏幕外)
②ios中不能复制属性值,只能复制文本元素节点;(解决方案:可以把文字颜色设成背景色就能达到隐藏看不见的效果不影响显示);
②今天咱们只会用到 copy .
简介里说 当文档对象被转换为设计模式的时候(选中,设置contentEditable等),文档对象提供了一个execCommand方法.
但是咱们根本不想出现一个 textarea 好嘛, 否则和window.prompt有啥区别呢?
最简单最有效的方式就是把 textarea 给隐藏起来嘛
js代码
copy = () => {
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {//区分iPhone设备
console.log('ios')
window.getSelection().removeAllRanges();//这段代码必须放在前面否则无效
var Url2=document.getElementById("copy");//要复制文字的节点
var range = document.createRange();
// 选中需要复制的节点
range.selectNode(Url2);
// 执行选中元素
window.getSelection().addRange(range);
// 执行 copy 操作
var successful = document.execCommand('copy');
// 移除选中的元素
window.getSelection().removeAllRanges();
}else{
var text = document.getElementById("copy").innerText;
const textarea = document.createElement("textarea") ;
textarea.style.position = 'fixed' ;
textarea.style.top = 0 ;
textarea.style.left = 0 ;
textarea.style.border = 'none' ;
textarea.style.outline = 'none' ;
textarea.style.resize = 'none';
textarea.style.background = 'transparent' ;
textarea.style.color = 'transparent';
textarea.value = text ;// 修改文本框的内容
document.body.appendChild(textarea);
textarea.select()// 选中文本
try { const msg = document.execCommand('copy') ?
'successful' : 'unsuccessful' ;
alert(msg)
} catch (err) { alert('unable to copy', err) }
document.body.removeChild(textarea)
}
}
jsp代码
<div className='button' style={{marginTop:'1rem'}}>保存二维码到手机</div>
<div style={{marginTop: '0.5rem'}} className='flex'>
<div className='button left-button'>微信号:<span id='copy'>ZYYLAPP</span></div>
<div className='button right-button' onClick={()=>{
this.copy()
}}>复制</div>