如何利用execCommand做一个简单的富文本编译器
2024-11-21 23:44:02
execCommand、富文本
2553

一、document.execCommand()方法

document.execCommand()方法处理html数据时常用语法格式如下:

document.execCommand(sCommand[,交互方式, 动态参数])

二、document.execCommand()的参数

  1. 全选document.execCommand(”selectAll”);
  2. 另存为document.execCommand(”saveAs”);
  3. 打印document.execCommand(”print”);
  4. 剪贴document.execCommand(”Cut”,”false”,null);
  5. 删除document.execCommand(”Delete”,”false”,null);
  6. 改变字体document.execCommand(”FontName”,”false”,sFontName);
  7. 改变字体大小document.execCommand(”FontSize”,”false”,sSize|iSize);
  8. 改变字体颜色document.execCommand(”ForeColor”,”false”,sColor);
  9. 改变背景颜色;document.execCommand(”BackColor”,”false”,sColor);
  10. 加粗document.execCommand(”Bold”,”false”,null);
  11. 复制ocument.execCommand(”Copy”,”false”,null);
  12. 锚点书签document.execCommand(”CreateBookmark”,”false”,sAnchorName);
  13. 将选中文本变成超连接document.execCommand(”CreateLink”,”false”,sLinkURL);若第二个参数为true,会出现参数设置对话框;
  14. 设置当前块的标签名document.execCommand(”FormatBlock”,”false”,sTagName);

三、具体实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>如何利用execCommand做一个简单的富文本编译器</title>
    <style>
        xr-editor {
  margin: 50px auto;
  width: 1000px;
}
  .nav {
    display: flex;
  
  }
  button {
      cursor: pointer;
    }
    
  .row {
    display: flex;
    width: 100%;
    height: 300px;
  }
  .editor {
    flex: 1;
    position: relative;
    margin-right: 20px;
    padding: 10px;
    outline: none;
    border: 1px solid #000;
    overflow-y: scroll;
  
  }
  .editor img {
      max-width: 300px;
      max-height: 300px;
      vertical-align: middle;
    }
  .content {
    flex: 1;
    border: 1px solid #000;
    word-break: break-all;
    word-wrap: break-word;
    overflow: scroll;
  }


    </style>
</head>
<body>
    <div id="app">
        <div class="xr-editor">
            <!--按钮区-->
            <div class="nav">
                <button @click="execCommand('bold')">加粗</button>
                <button @click="execCommand('fontname','宋体')">宋体</button>
                <button @click="execCommand('foreColor','red')">红色</button>
                <button @click="execCommand('fontSize','24')">24px</button>
                <button @click="execCommand('formatBlock','h1')">h1</button>
                <button @click="execCommand('selectAll',null)">全选</button>
                <button @click="execCommand('CreateLink',true)">清除格式</button>
                
            </div>
            <!--编辑区-->
            <div class="editor" contenteditable="true"></div>
        </div>
      </div>
</body>
<script src="https://www.jq22.com/jquery/vue.min.js"></script>
<script>
    var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  methods: {
    execCommand(name,data) {
        //加粗
      document.execCommand(name, false, data);
    }
  }
})
</script>
</html>