Визуальный редактор для html javascript

Пишем простейший WYSIWYG (визуальный редактор) на Javascript

Задача: написать простейший визуальный редактор и немного разобраться как он работает.

Что такое WYSIWYG?

WYSIWYG — аббревиатура What You See Is What You Get. В переводе: «что вижу, то и получаю». В висивиге можно просматривать и редактировать HTML-содержимое не редактируя HTML-код. Наиболее близкая аналогия ВИСИВИГу — это текстовый процессор от Microsoft Word, с которым многие знакомы. В нем, чтобы поставить жирность или курсив, не нужно писать теги или другие элементы форматирования, достаточно просто нажать соотствующую функциональную кнопку.

Как это работает?

Для написания простого ВИСИВИГа не нужно изобретать велосипед, все средства уже встроены и успешно работают. Механизм работы большинства визуальных редакторов основан на свойстве designMode объекта document. Это встроенное свойство (к сожалению, далеко не для всех браузеров, но для большинства современных) как раз и позволяет редактировать HTML-контент. После его активанции (designMode=’On’) на web-страницу можно ставить привычный нам курсор и набивать, удалять или изменять форматирование контента.

Бывает удобно не редактировать всю страницу, а иметь какую-то фиксированную область, для чего используется iframe. Именно его объект document используется для активации свойства designMode.

Форматирование содержимого в пределах ВИСИВИГа осуществляется с помощью непростого метода execCommand, реализация которого сильно различается от браузера к браузеру.

Смотрим JavaScript-код для простейшего ВИСИВИГа:

// *********************** // ШАГ 1: Выводим iframe и получаем доступ к нему // *********************** // Выводим в HTML-поток iframe document.write(»
«); // Определим Gecko-браузеры, т.к. они отличаются в своей работе от Оперы и IE var isGecko = navigator.userAgent.toLowerCase().indexOf(«gecko») != -1; // Получаем доступ к объектам window & document для ифрейма var iframe = (isGecko) ? document.getElementById(«frameId») : frames[«frameId»]; var iWin = (isGecko) ? iframe.contentWindow : iframe.window; var iDoc = (isGecko) ? iframe.contentDocument : iframe.document; // *********************** // ШАГ 2: Добавим на пустую страницу ифрейма произвольный HTML-код // *********************** // Формируем HTML-код iHTML = «n»; iHTML += «

n»; iHTML += «Содержимое с HTMLразметкой«; iHTML += ««; // Добавляем его с помощью методов объекта document iDoc.open(); iDoc.write(iHTML); iDoc.close(); // *********************** // ШАГ 3: Инициализация свойства designMode объекта document // *********************** if (!iDoc.designMode) alert(«Визуальный режим редактирования не поддерживается Вашим браузером»); else iDoc.designMode = (isGecko) ? «on» : «On»; // *********************** // ШАГ 4: Простейшие элементы редактирования: жирность, курсив, подчеркивание // *********************** // Выведем HTML-код этих элементов document.write(«»); document.write(«»); document.write(«»); // Запишем код функции, для выставления форматирования // Используется метод execCommand объекта document function setBold() < iWin.focus(); iWin.document.execCommand("bold", null, ""); >function setItal() < iWin.focus(); iWin.document.execCommand("italic", null, ""); >function setUnder()

Читайте также:  Web portal html template

Данная версия визуального редактора не может работать в Опере ниже версии 9.01 и покажет предупреждение «Визуальный режим редактирования не поддерживается Вашим браузером». Работоспособность проверена в:
— IE 6;
— FF 1.5;
— Opera 9.01 +;
— Mozilla 1.7.2;
— NN 7.1 +;

Источник

JavaScript wysiwyg редакторы

Довольно часто для моих проектов требуется надежный wysiwyg редактор для форматирования статей и различной сложности текстов. Ниже список наиболее интересных на мой взгляд решений.

FroalaEditor

Простой и легковесный, с богатым API, адаптированный под огромное количество фреймфорков он также оснащен мощным защитным механизмом против атак XSS.

ContentTools

ContentTools — небольшой и красивый редактор контента. В библиотеке не используется какой-либо JavaScript-фреймворк или библиотека (даже jQuery), но отлично работает с любым из них. Пакет ContentTools состоит из 5 библиотек, каждый из которых может использоваться независимо. Он разработан, чтобы его было легко расширить.

TinyMCE

TinyMCE — независимый от платформы веб-интерфейс JavaScript HTML WYSIWYG. Это позволяет вам конвертировать поля текстовой области HTML или другие элементы HTML в экземпляры редакторов. Вы можете загружать и управлять файлами на Microsoft Azure, Google Диске, Amazon S3, DropBox и других. Он следует спецификациям WAI-ARIA, что делает его совместимым с программами чтения с экрана, такими как JAWS и NVDA. Существует также корпоративное решение, в котором вы получаете приоритетную поддержку.

Summernote

Summernote — текстовый редактор, основанный на Bootstrap. Для него доступны различные темы, и они работают от Bootswatch. Существует также версия, конвертированная в материальную тему MaterialNote

Quill

Мощный и с богатым API тектовый редактор, в то же время очень легковесный.

MediumEditor

Небольшой (всего 28kb) встраиваемый на страницу редактор от разработчиков Medium.com. Есть довольно неплохой набор расширейни.

CKEditor4

CKEditor — это готовый к использованию текстовый редактор HTML, предназначенный для упрощения создания веб-контента. Он привносит общие функции текстовых процессоров прямо на ваши веб-страницы.

Redactor

Redactor — быстрый, мощный и расширяемый редактор с группой поддержки качества. Он существует уже 7 лет и находится в стадии активного развития. Он также автоматически загружает изображения в Amazon S3.

PS:

Я надеюсь, что этот список поможет вам выбрать хороший текстовый редактор для вашего проекта и сэкономить время на поиске плагина, который наилучшим образом соответствует вашим потребностям.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Читайте также:  Python struct pack float

The next generation Javascript WYSIWYG HTML Editor.

License

froala/wysiwyg-editor

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Froala WYSIWYG HTML Editor is one of the most powerful JavaScript rich text editors ever.

WYSIWYG HTML Editor

  • Slim — only add the plugins that you need (30+ official plugins)
  • Client frameworks integrations
  • Server side SDKs for PHP, Node.JS, .NET, Java, and Python
  • Code is well commented
  • Online documentation up to date
  • Simple to extend — the plugins are all well commented and simple to use as a basis for your own plugins
  • Well maintained — frequent releases
  • Great support — Help Center
  • Awesome new features ​
  • Basic demo: https://www.froala.com/wysiwyg-editor
  • Inline demo: https://www.froala.com/wysiwyg-editor/inline
  • Full list: https://www.froala.com/wysiwyg-editor/examples

Download and Install Froala Editor

bower install froala-wysiwyg-editor 

Using Froala Editor from CDN is the easiest way to install it and we recommend using the jsDeliver CDN as it mirrors the NPM package.

 link href pl-s">https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel pl-s">stylesheet" type pl-s">text/css" />  textarea>textarea> script type pl-s">text/javascript" src pl-s">https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js">script> script> new FroalaEditor('textarea'); script>

Load from CDN as an AMD module

Froala Editor is compatible with AMD module loaders such as RequireJS. The following example shows how to load it along with the Algin plugin from CDN using RequireJS.

html> head> link rel pl-s">stylesheet" type pl-s">text/css" href pl-s">https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.css"> script src pl-s">require.js">script> script> require.config( packages: [ name: 'froala-editor', main: 'js/froala_editor.min' >], paths:  // Change this to your server if you do not wish to use our CDN. 'froala-editor': 'https://cdn.jsdelivr.net/npm/froala-editor@latest' > >); script> style> body < text-align: center; > div#editor < width: 81%; margin: auto; text-align: left; > .ss < background-color: red; > style> head> body> div id pl-s">editor"> div id='edit' style='margin-top:30px;'> div> div> script> require([ 'froala-editor', 'froala-editor/js/plugins/align.min' ], function(FroalaEditor)  new FroalaEditor('#edit') >); script> body> html>

Load Froala Editor as a CommonJS Module

Froala Editor is using an UMD module pattern, as a result it has support for CommonJS. The following examples presumes you are using npm to install froala-editor, see Download and install FroalaEditor for more details.

var FroalaEditor = require('froala-editor'); // Load a plugin. require('froala-editor/js/plugins/align.min'); // Initialize editor. new FroalaEditor('#edit');

Load Froala Editor as a transpiled ES6/UMD module

Since Froala Editor supports ES6 (ESM — ECMAScript modules) and UMD (AMD, CommonJS), it can be also loaded as a module with the use of transpilers. E.g. Babel, Typescript. The following examples presumes you are using npm to install froala-editor, see Download and install FroalaEditor for more details.

import FroalaEditor from 'froala-editor' // Load a plugin. import 'froala-editor/js/plugins/align.min.js' // Initialize editor. new FroalaEditor('#edit')

For more details on customizing the editor, please check the editor documentation.

Use with your existing framework

  • Angular JS: https://github.com/froala/angular-froala
  • Angular 2: https://github.com/froala/angular2-froala-wysiwyg
  • Aurelia: https://github.com/froala/aurelia-froala-editor
  • CakePHP: https://github.com/froala/wysiwyg-cake
  • Craft 2 CMS: https://github.com/froala/Craft-Froala-WYSIWYG
  • Craft 3 CMS: https://github.com/froala/Craft-3-Froala-WYSIWYG
  • Django: https://github.com/froala/django-froala-editor
  • Ember: https://github.com/froala/ember-froala-editor
  • Knockout: https://github.com/froala/knockout-froala
  • Meteor: https://github.com/froala/meteor-froala
  • Ruby on Rails: https://github.com/froala/wysiwyg-rails
  • React JS: https://github.com/froala/react-froala-wysiwyg/
  • Reactive: https://github.com/froala/froala-reactive
  • Symfony: https://github.com/froala/KMSFroalaEditorBundle
  • Vue JS: https://github.com/froala/vue-froala-wysiwyg/
  • Yii2: https://github.com/froala/yii2-froala-editor
  • WordPress: https://github.com/froala/wordpress-froala-wysiwyg

At present, we officially aim to support the last two versions of the following browsers:

  • Chrome
  • Edge
  • Firefox
  • Safari
  • Opera
  • Internet Explorer 11
  • Safari iOS
  • Chrome, Firefox and Default Browser Android
  • Demo: www.froala.com/wysiwyg-editor
  • Download Page: www.froala.com/wysiwyg-editor/download
  • Documentation: froala.com/wysiwyg-editor/docs
  • License Agreement: www.froala.com/wysiwyg-editor/terms
  • Support: wysiwyg-editor.froala.help
  • Roadmap & Feature Requests: https://wysiwyg-editor-roadmap.froala.com
  • Issues Repo guidelines

We use GitHub Issues as the official bug tracker for the Froala WYSIWYG HTML Editor. Here are some advices for our users that want to report an issue:

  1. Make sure that you are using the latest version of the Froala WYSIWYG Editor. The issue that you are about to report may be already fixed in the latest master branch version: https://github.com/froala/froala-wysiwyg/tree/master/js.
  2. Providing us reproducible steps for the issue will shorten the time it takes for it to be fixed. A JSFiddle is always welcomed, and you can start from this basic one.
  3. Some issues may be browser specific, so specifying in what browser you encountered the issue might help.

Technical Support or Questions

If you have questions or need help integrating the editor please contact us instead of opening an issue.

In order to use the Froala Editor you have to purchase one of the following licenses according to your needs. You can find more about that on our website on the pricing plan page.

About

The next generation Javascript WYSIWYG HTML Editor.

Источник

Оцените статью