Предпросмотр текста
Код:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Автоматический предпросмотр</title>
<style>
.preview {
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
max-height: 200px;
overflow-y: auto;
}
</style>
</head>
<body>
<textarea id="editor" placeholder="Введите текст..."></textarea>
<div class="preview" id="previewElement"></div>
<script>
let watcherTimeout;
function updatePreview() {
clearTimeout(watcherTimeout);
const text = document.getElementById('editor').value;
const previewElement = document.getElementById('previewElement');
previewElement.textContent = text;
previewElement.style.maxHeight = `200px`;
if (text.length > 0) {
previewElement.style.maxHeight = `200px`;
} else {
previewElement.style.maxHeight = `0`; // Скрываем, если текст пустой
}
}
// Запускаем первую проверку сразу после заполнения поля
updatePreview();
// Следим за изменением текста
document.getElementById('editor').addEventListener('input', updatePreview);
// Опция для остановки наблюдения
function stopWatching() {
watcherTimeout = setTimeout(updatePreview, 500); // Проверка каждые 500 мс
}
// Опция для очистки
function clearWatching() {
clearTimeout(watcherTimeout);
updatePreview(); // При необходимости можно снова запустить наблюдение
}
// Добавляем кнопки для удобства
function togglePreview() {
if (watcherTimeout) {
clearWatching();
} else {
watcherTimeout = setTimeout(updatePreview, 500);
}
}
</script>
</body>
</html>