search
HomeWeb Front-endHTML TutorialCreate 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.

Document.execCommand()

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.

Command without value parameter

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 with value parameters

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.

Command to add block style tag

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.

Create toolbar

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 方法的适当版本。它有助于编写简洁的代码并避免重复。

设置 foreColorbackColor 时,我使用 data-value 属性作为第三个参数。 createLinkinsertImage 没有常量 url 值,因此我们使用提示从用户获取值。您可能还想执行其他检查以确保 url 有效。如果command变量不满足任何if块,我们运行第一个版本的execCommand。

这就是我们所见即所得编辑器的样子。

Create a WYSIWYG editor using the contentEditable property

您还可以使用我在上次讨论的 localStorage 来实现自动保存功能教程。

跨浏览器差异

各种浏览器在实现上存在细微差异。例如,请记住,使用 formatBlock 时,Internet Explorer 仅支持标题标签 h1 - h6addresspre。在指定 commandName 时,您还需要包含标记分隔符,例如 <h3></h3>

并非所有浏览器都支持所有命令。 Internet Explorer 不支持 insertHTMLhiliteColor 等命令。同样,只有 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.