JSFiddle - React, Tailwind, and code Playground
by Yoghurts
HTML
<div id="ua"></div>
<button id="btn">
copy
</button>
JavaScript
const copyToClipboard = input => {
const el = document.createElement('textarea');
el.value = input;
// Prevent keyboard from showing on mobile
el.setAttribute('readonly', '');
el.style.contain = 'strict';
el.style.position = 'absolute';
el.style.left = '-9999px';
el.style.fontSize = '12pt'; // Prevent zooming on iOS
const selection = document.getSelection();
let originalRange = false;
if (selection.rangeCount > 0) {
originalRange = selection.getRangeAt(0);
}
document.body.appendChild(el);
el.select();
// Explicit selection workaround for iOS
el.selectionStart = 0;
el.selectionEnd = input.length;
let success = false;
try {
success = document.execCommand('copy');
} catch (err) {
// eslint-disable-next-line
console.error(err)
}
document.body.removeChild(el);
if (originalRange) {
selection.removeAllRanges();
selection.addRange(originalRange);
}
if (!success) {
setTimeout(() => {
// eslint-disable-next-line
window.prompt('复制失败,请手动复制:', input);
}, 200);
} else {
alert('复制成功');
}
};
const ua = document.getElementById("ua");
const btn = document.getElementById("btn");
if(ua) {
ua.innerHTML = window.navigator.userAgent;
}
if(btn) {
btn.addEventListener('click', () => {
copyToClipboard(window.navigator.userAgent)
})
}