JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="textareaToCopy">Кликни сюда, чтобы скопировать. Кроме того, этот текст скопируется, когда ты уберёшь фокус из этого поля.</textarea>
CSS
*,
:before,
:after {
box-sizing: border-box;
}
textarea {
width: 100%;
max-width: 400px;
font-size: 20px;
line-height: 1.5;
min-height: 7.5em;
resize: none;
border: none;
-webkit-appearance: none;
border-radius: 10px;
padding: 10px;
background-color: #fff;
box-shadow: 0 0 10px 0 #999;
transition: box-shadow .1s;
}
textarea:active {
box-shadow: 0 0 10px 0 #004fff;
}
JavaScript
// Для старых браузеров
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
// Для нормальных браузеров
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}
//
//
//
//
//
//
// Слушаем клик по textarea с id="textareaToCopy"
textareaToCopy.onclick = function() {
copyTextToClipboard(this.value); // Копируем
textareaToCopy.focus(); // Возвращаем фокус
};
// Слушаем смену фокуса у textarea с id="textareaToCopy". Когда пользователь убирает фокус, копируем оттуда текст
textareaToCopy.onblur = function() {
copyTextToClipboard(this.value); // Копируем
};