富文本的原理:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>富文本</title> <style> #box{ 300px; height: 300px; border: 1px solid #ccc; } </style> </head> <body> <button onclick="boldHandler()">加粗</button> <button onclick="italicHandler()">倾斜</button> <button onclick="colorHandler()">颜色</button> <div contenteditable id="box"></div> <!-- 引入富文本 --> <script src="https://unpkg.com/wangeditor@3.1.1/release/wangEditor.min.js"></script> <script> function boldHandler(){ document.execCommand("bold"); } function italicHandler(){ document.execCommand("italic"); } function colorHandler(){ document.execCommand("foreColor",null,"deeppink"); } </script> </body> </html>
效果:
插件使用:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>富文本</title> </head> <body> <div id="editor"> <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p> </div> <!-- 引入富文本 --> <script src="https://unpkg.com/wangeditor@3.1.1/release/wangEditor.min.js"></script> <script type="text/javascript"> var E = window.wangEditor var editor = new E('#editor') // 或者 var editor = new E( document.getElementById('editor') ) editor.create() </script> </body> </html>
效果: