营销网站占用多少m空间,大连市建设厅网站,如何免费做网站优化,网站如何建设手机版javascript复制到黏贴板之完美兼容
很多时候我们需要给用户方便,提供一键复制的功能,但是在实现的过程中遇到各式各样的坑。
原生解决方案
document.execCommand()方法
MDN上的定义#xff1a; which allows one to run commands to manipulate the contents of the edita…javascript复制到黏贴板之完美兼容
很多时候我们需要给用户方便,提供一键复制的功能,但是在实现的过程中遇到各式各样的坑。
原生解决方案
document.execCommand()方法
MDN上的定义 which allows one to run commands to manipulate the contents of the editable region. 当一个HTML文档切换到设计模式 designMode时document暴露 execCommand 方法该方法允许运行命令来操纵可编辑区域的内容。 使用方式
函数语法 bool document.execCommand(aCommandName, aShowDefaultUI, aValueArgument) aCommandName 表示命令名称比如 copy, cut 等更多命令访问aShowDefaultUI是否展示用户界面一般为 false。Mozilla 没有实现aValueArgument一些命令例如insertImage需要额外的参数insertImage需要提供插入image的url默认为null
兼容性 目前除了 安卓UC浏览器、Opera Mini、安卓原生浏览器 外其他都支持。
使用教程
如果目标是input元素
!--html--
input iddemoInput valuehello world
button idbtn点我复制/button!--JavaScript--
const btn document.querySelector(#btn);
btn.addEventListener(click, () {const input document.querySelector(#demoInput);input.select();if (document.execCommand(copy)) {document.execCommand(copy);console.log(复制成功);}
})如果目前是非input元素
!--html--
button idbtn (click)copy()点我复制/button
span idcopy-text/span!--JavaScript--
function copy() {const content document.getElementById(copy-text);const input document.createElement(input);input.setAttribute(readonly, readonly);input.setAttribute(value, content.innerHTML);document.body.appendChild(input);input.focus();input.setSelectionRange(0, input.value.length);if (document.execCommand(copy)) {document.execCommand(copy);console.log(复制成功);} else {console.log(复制失败);}document.body.removeChild(input);
}
遇到的坑 复制的时候ios手机会出现键盘弹出又瞬间收回。这是因为输入框聚焦造成的。 解决办法,增加下面一段让input只读不能输入就不会出现了。 input.setAttribute(readonly, readonly);input.select()在ios下不能选中全部内容更换input.setSelectionRange(0, input.value.length);方法。
END