原生JS实现
原生JS,先使用select()
选中输入框文本,然后使用document.execCommand("Copy")
复制到剪贴板
前提条件
select()
方法只对<input>
和<textarea>
有效输入框不能有disabled
属性输入框不能有hidden
属性输入框的width
和height
不能为0
实现代码
HTML
<div><input id="copyInput" type="text" value="需要复制的文本" /></div>
JS
var ele = document.getElementById("copyInput");ele.select();let c = document.execCommand("Copy");if (c) {alert("复制链接成功!");} else {alert("复制失败!当前浏览器不支持此功能,请手动复制。");}