html+js实现点击按钮复制文本内容到剪切板上,有时候我们可能需要点击一个按钮自动复制反显信息到剪切板,无须多言直接上代码。
html
<input id="text" value="复制我呀" disabled/>
<button id="demo">复制</button>
js
const oBtn = document.querySelector('#demo');
oBtn.onclick = (e) => {
const text = document.querySelector('#text').value;
/*select() 方法用于选择该元素中的文本,
元素的disabled属性会让select方法失效,
所以重新创建了一个input
*/
const oInput = document.createElement('input');
oInput.value = text
document.body.appendChild(oInput)
//选中新的input里面的值
oInput.select();
//执行复制命令
document.execCommand("copy");
document.body.removeChild(oInput);
}
复制到了值,收工。