我想要能够在点击时复制文本字符串,而不需要按钮。文本字符串将位于一个"span"类中。
- 用户将鼠标悬停在文本字符串上
- 用户点击文本字符串
- 文本字符串被复制到剪贴板
let textString = document.querySelector('span.textstring').textContent; //Get value of the string you want to copy
const copyText = async () => {
try {
await navigator.clipboard.writeText(textString);
console.log('Content copied to clipboard!');
} catch (err) {
console.log('Copy failed!');
}
}
document.querySelector('span.textstring').addEventListener('click', copyText); //Add the event handler click, so when the span is clicked, the value is copied
灵感和适应来源于:https://www.freecodecamp.org/news/copy-text-to-clipboard-javascript/
function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}
<p onclick="copy(this)">hello man</p>