原生JS实现复制文本功能
原生JS实现复制功能。
使用的是DOM的execCommand。
<input type="text">
<button onClick="copyFn()">点击复制</button>
<script>
function copyFn(){
let txt=document.getElementsByTagName('input')[0].value;
copy(txt);
}
function copy(item){
let span=document.createElement('span');
let Text=document.createTextNode(item);
span.appendChild(Text);
document.body.appendChild(span);
window.getSelection().selectAllChildren(span);
document.execCommand ("Copy");
document.body.removeChild(span);
}
</script>
创建html元素,因为execCommand必须复制存在于页面上的标签元素,等文本复制到剪切板后,再移除元素。