/
ren4
/
simplt_html_editor
Обзор
Документация
Войти
/
ren4
/
simplt_html_editor
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
script.js
99 строк
3 KB
ren4
feat: Initial commit
21 июн 2025, 16:02
21 июн 2025, 16:02
4bdfeb9
Код
Авторство
О чём код?
document.addEventListener("DOMContentLoaded", function () { const editor = document.getElementById("editor"); const toolbarButtons = document.querySelectorAll( ".toolbar button, .toolbar select" ); // Обработка команд форматирования toolbarButtons.forEach((button) => { button.addEventListener("click", function () { const command = this.getAttribute("data-command"); const value = this.value || null; if (command === "undo" || command === "redo") { // Для undo/redo можно использовать свою реализацию handleUndoRedo(command); } else { formatText(command, value); } editor.focus(); }); }); // Инициализация редактора editor.addEventListener("click", function () { if (this.innerHTML === "Начните вводить текст здесь...") { this.innerHTML = ""; } }); editor.addEventListener("blur", function () { if (this.innerHTML === "") { this.innerHTML = "Начните вводить текст здесь..."; } }); // Современная реализация форматирования function formatText(command, value = null) { const selection = window.getSelection(); if (selection.rangeCount === 0 || !selection.toString()) return; const range = selection.getRangeAt(0); let newNode; switch (command) { case "bold": newNode = document.createElement("strong"); break; case "italic": newNode = document.createElement("em"); break; case "underline": newNode = document.createElement("u"); break; case "strikeThrough": newNode = document.createElement("s"); break; case "formatBlock": if (value) { const blockElement = document.createElement(value); range.surroundContents(blockElement); return; } break; default: return; } // Применяем форматирование к выделенному тексту range.surroundContents(newNode); } // Простая реализация undo/redo const editorStates = []; let currentState = -1; editor.addEventListener("input", () => { // Сохраняем состояние при каждом изменении const html = editor.innerHTML; if (html === editorStates[currentState]) return; // Удаляем все состояния после текущего editorStates.splice(currentState + 1); editorStates.push(html); currentState = editorStates.length - 1; }); function handleUndoRedo(action) { if (action === "undo" && currentState > 0) { currentState--; } else if (action === "redo" && currentState < editorStates.length - 1) { currentState++; } else { return; } editor.innerHTML = editorStates[currentState]; } });