---
date: 2021-02-20
title: JavaScript 写一个简易富文本编辑器
category: experience
cover: https://tse4-mm.cn.bing.net/th/id/OIP-C.qfGMxV5hvspQlidAAoZOGgHaDt?pid=ImgDet&rs=1
recommend: true
location: 甘肃
tags:
  - JavaScript
  - 富文本编辑器
---

``` html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #editor {
        width: 600px;
        margin: 0 auto;
        background-color: #f5f5f5;
        height: 300px;
        padding: 15px;
      }

      .tools button {
        background-color: #000;
        color: #fff;
        font-size: 14px;
        padding: 5px 8px;
        cursor: pointer;
      }

      .content {
        position: relative;
        height: 85%;
        padding: 15px;
        outline: 0;
      }

      .content p {
        margin: 0;
      }
    </style>
  </head>
  <body>
    <div id="editor">
      <div class="tools">
        <button onclick="document.execCommand('bold', false, null)">加粗</button>
        <button onclick="document.execCommand('strikeThrough', false, null)">划线</button>
        <button onclick="document.execCommand('foreColor', false, 'red')">红色</button>
      </div>
      <div class="content" id="content" contenteditable>
        <p>请输入...</p>
      </div>
    </div>
  </body>
</html>
```