Home >Web Front-end >HTML Tutorial >Create a WYSIWYG editor using the contentEditable property
WYSIWYG editors are very popular. You've probably also used one of these at some point. There are many libraries available to help you set up your own editor. Although they are quick to set up, there are drawbacks to using these libraries. First, they are bloated. Most of them have fancy features that you probably won't use. Additionally, customizing the appearance of these editors can be a headache.
In this tutorial, we will build our own lightweight WYSIWYG editor. By the end of this tutorial, you will have an editor with basic formatting capabilities that you can style to your liking.
We first introduce execCommand
. We will use this command to implement our editor extensively.
execCommand
is a method of the document object. It allows us to manipulate the contents of the editable area. When used with contentEditable
, it can help us create rich text editors. There are many commands available, such as adding links, setting the selection to Bold or Italic, and changing the font size or color. The method follows the following syntax:
document.execCommand(CommandName, ShowDefaultUI, ValueArgument);
CommandName
is a string specifying the name of the command to be executed. ShowDefaultUI
is a Boolean value indicating whether the support interface should be displayed. This option is not fully implemented yet and is best set to false. ValueArgument
is a string that provides information such as an image URL or foreColor
. This parameter is set to null
when the command does not require a value to take effect.
We need to use different versions of this method to achieve various functions. In the next few paragraphs I will review them one by one.
Commands such as bold, align, undo and redo do not require a ValueArgument
. In this case we use the following syntax:
document.execCommand(commandName, false, null);
CommandName
is just the name of the command, such as justifyCenter
, justifyRight
, bold
, etc.
Commands like insertImage
, createLink
and foreColor
require a third argument to work properly. For these commands you need the following syntax:
document.execCommand(commandName, false, value);
For insertImage
, the value is the URL of the image to be inserted. For foreColor
, it will be a color value like #FF9966
or a name like blue
.
Adding HTML block style tags requires using formatBlock
as commandName
and the tag name as valueArgument
. The syntax is similar to:
document.execCommand('formatBlock', false, tagName);
This method will add HTML block style tags around the row containing the current selection. It will also replace any tags that are already there. tagName
can be any title tag (h1
-h6
), p
, or blockquote
.
I have discussed the most commonly used commands here. You can visit Mozilla for a list of all available commands.
After the basics are completed, it’s time to create the toolbar. I will use Font Awesome icon for the button. You may have noticed that, aside from a few differences, all execCommand
have a similar structure. We can take advantage of this by using the following markup for the toolbar buttons:
<a href="#" data-command='commandName'><i class='fa fa-icon'></i></a>
This way, whenever the user clicks the button, we can determine which version of execCommand
to use based on the value of the data-command
attribute. Here are a few buttons for reference:
<a href="#" data-command='h2'>H2</a> <a href="#" data-command='undo'><i class='fa fa-undo'></i></a> <a href="#" data-command='createlink'><i class='fa fa-link'></i></a> <a href="#" data-command='justifyLeft'><i class='fa fa-align-left'></i></a> <a href="#" data-command='superscript'><i class='fa fa-superscript'></i></a>
The data-command
attribute value of the first button is h2
. After checking this value in JavaScript, we will use the formatBlock
version of the execCommand
method. Likewise, for the last button, superscript
recommends that we use the execCommand
version without the valueArgument
.
Creating the foreColor
and backColor
buttons is another story. They pose two problems. Depending on the number of colors we offer the user to choose from, writing so much code can be annoying and error-prone. To solve this problem, we can use the following JavaScript code:
var colorPalette = ['000000', 'FF9966', '6699FF', '99FF66','CC0000', '00CC00', '0000CC', '333333', '0066FF', 'FFFFFF']; var forePalette = $('.fore-palette'); for (var i = 0; i < colorPalette.length; i++) { forePalette.append('<a href="#" data-command="forecolor" data-value="' + '#' + colorPalette[i] + '" style="background-color:' + '#' + colorPalette[i] + ';" class="palette-item"></a>'); }
请注意,我还为每种颜色设置了一个 data-value
属性。稍后它将在 execCommand
方法中用作 valueArgument
。
第二个问题是我们不能一直显示那么多颜色,因为这会占用大量空间并导致糟糕的用户体验。使用一点CSS,我们可以确保只有当用户将鼠标悬停在相应按钮上时才会出现调色板。这些按钮的标记也需要更改为以下内容:
<div class="fore-wrapper"><i class='fa fa-font'></i> <div class="fore-palette"> </div> </div>
要仅在 hover
上显示调色板,我们需要以下 CSS:
.fore-palette, .back-palette { display: none; } .fore-wrapper:hover .fore-palette, .back-wrapper:hover .back-palette { display: block; float: left; position: absolute; }
CodePen 演示中还有许多其他 CSS 规则可以使工具栏更漂亮,但这就是核心功能所需的全部。
现在,是时候让我们的编辑器发挥作用了。这样做所需的代码非常小。
$('.toolbar a').click(function(e) { var command = $(this).data('command'); if (command == 'h1' || command == 'h2' || command == 'p') { document.execCommand('formatBlock', false, command); } if (command == 'forecolor' || command == 'backcolor') { document.execCommand($(this).data('command'), false, $(this).data('value')); } if (command == 'createlink' || command == 'insertimage') { url = prompt('Enter the link here: ','http:\/\/'); document.execCommand($(this).data('command'), false, url); } else document.execCommand($(this).data('command'), false, null); });
我们首先将单击事件附加到所有工具栏按钮。每当单击工具栏按钮时,我们都会将相应按钮的 data-command
属性的值存储在变量 command
中。稍后将用于调用 execCommand
方法的适当版本。它有助于编写简洁的代码并避免重复。
设置 foreColor
和 backColor
时,我使用 data-value
属性作为第三个参数。 createLink
和 insertImage
没有常量 url
值,因此我们使用提示从用户获取值。您可能还想执行其他检查以确保 url
有效。如果command变量不满足任何if块,我们运行第一个版本的execCommand。
这就是我们所见即所得编辑器的样子。
您还可以使用我在上次讨论的 localStorage
来实现自动保存功能教程。
各种浏览器在实现上存在细微差异。例如,请记住,使用 formatBlock
时,Internet Explorer 仅支持标题标签 h1 - h6
、address
和 pre
。在指定 commandName
时,您还需要包含标记分隔符,例如 <h3></h3>
。
并非所有浏览器都支持所有命令。 Internet Explorer 不支持 insertHTML
和 hiliteColor
等命令。同样,只有 Firefox 支持 insertBrOnReturn
。您可以在此 GitHub 页面上了解有关浏览器不一致的更多信息。
创建您自己的所见即所得编辑器可以是一次很好的学习体验。在本教程中,我介绍了很多命令并使用了一些 CSS 来进行基本样式设置。作为练习,我建议您尝试实现一个工具栏按钮来设置文本选择的 font
。该实现与 foreColor
按钮的实现类似。
我希望您喜欢本教程并学到一些新东西。如果您从头开始创建了自己的所见即所得编辑器,请随时在评论部分链接到它。
The above is the detailed content of Create a WYSIWYG editor using the contentEditable property. For more information, please follow other related articles on the PHP Chinese website!