JSFiddle - React, Tailwind, and code Playground
by Miken912
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy to Clipboard</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="copy-container">
<div class="copy-text">Первый текст для копирования!</div>
<div class="copy-text">Второй текст для копирования!</div>
<div class="copy-text">Третий текст для копирования!</div>
</div>
<div id="notification" class="notification">Текст скопирован!</div>
<script src="script.js"></script>
</body>
</html>
CSS
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f4;
}
.copy-container {
display: flex;
flex-direction: column;
gap: 10px;
}
.copy-text {
padding: 10px 20px;
background-color: #007bff;
color: white;
cursor: pointer;
border-radius: 5px;
width: max-content;
}
.notification {
position: absolute;
background-color: #4caf50;
color: white;
padding: 10px 20px;
border-radius: 5px;
opacity: 0;
transition: opacity 0.5s ease;
pointer-events: none;
}
JavaScript
document.querySelectorAll('.copy-text').forEach(function(copyTextDiv) {
copyTextDiv.addEventListener('click', function() {
// Получаем текст внутри div
const textToCopy = this.textContent;
// Копируем текст в буфер обмена
navigator.clipboard.writeText(textToCopy).then(() => {
// Показываем уведомление
const notification = document.getElementById('notification');
// Определяем позицию уведомления относительно нажатого блока
const rect = this.getBoundingClientRect();
notification.style.left = `${rect.left + window.scrollX}px`;
notification.style.top = `${rect.bottom + window.scrollY}px`;
// Показ уведомления
notification.classList.add('show');
// Через 3 секунды скрываем уведомление
setTimeout(function() {
notification.classList.remove('show');
}, 3000);
}).catch(err => {
console.error('Ошибка при копировании текста: ', err);
});
});
});