I didn’t come here until today, and I have a rough understanding of it. Of course, as for the process, it is painful in the first second and easy in the last three seconds. This rich text editor is mainly implemented using the contenteditable attribute document.execCommand() method that comes with p. In order to facilitate the layout, I was lazy and directly used the table layout. Alas, as a front-end developer in those years Staff, I really don’t know what to say.
The following shows the effect of the implementation:
The implementation process of the body:
(1) HTML structure:
<table border='1' class="tablebox" id='tablebox'> <tr> <td> <input type="button" name="bold" value='Bold' class="bold"> </td> <td> <input type="button" name="italic" value='Italic' class="italic"> </td> <td> <input type="button" name="underline" value='Underline' class="decotation"> </td> <td>size <select name="fontSize" class="font"> <option value="1">1</option> <option value="3">3</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> </select> </td> <td>img <select name="insertImage"> <option value="">请选择图片</option> <option value="timg.jpg">timg.jpg</option> <option value="timg1.jpg">timg1.jpg</option> <option value="timg2.jpg">timg2.jpg</option> <option value="timg3.jpg">timg3.jpg</option> <option value="timg4.jpg">timg4.jpg</option> </select> </td> <td> <input type="button" name="selectAll" value='全选' class="selectAll"> </td> <td> <input type="button" name="undo" value='撤销' class="undo"> </td> <td> <input type="button" name="justifyLeft" value='left' class="justifyLeft"> </td> <td> <input type="button" name="justifyCenter" value='center' class="justifyCenter"> </td> <td> <input type="button" name="justifyRight" value='right' class="justifyRight"> </td> </tr> <tr> <td colspan='10'> <p class="text" contenteditable="true">这是一个用p的contenteditable属性以及document.execCommand实现的一个简易富文本编辑器。</p> </td> </tr> </table>
(2) JS implementation logic:
(function() { //富文本编辑器类 class Editor { constructor() { this.bindElem(); } bindElem() { var text = document.querySelector('.text'); var txt = null; var tablebox = document.getElementById_x('tablebox'); var inputbs = tablebox.querySelectorAll('input,select'); for (var i = 0; i { if (inputbs[i].tagName.toLowerCase() == 'input') { this.action(inputbs[i], inputbs[i].name); } else if (inputbs[i].tagName.toLowerCase() == 'select') { inputbs[i].onchange = function() { document.execCommand(this.name, true, this.value); } } } } action(obj, attr) { obj.onclick = function() { document.execCommand(attr, true); } } } new Editor(); })();
Related recommendations:
A simple way to implement a JavaScript rich text editor
The above is the detailed content of JS simple version rich text editor implementation code. For more information, please follow other related articles on the PHP Chinese website!