<!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>原生JS實現簡單富文本編輯器</title> </head> <body> <center><h2 style="margin:auto;">原生JS實現簡單富文本編輯器</h2></center> <hr> <div id="toolbar" style="width:700px;margin:auto;border:2px solid gray;padding: 5px;overflow: auto;font-family: 'Courier New', Courier, monospace;"> <input type="button" name="bold" value='Bold' class="bold"> <input type="button" name="italic" value='Italic' class="italic"> <input type="button" name="underline" value='Underline' class="decotation"> </div> <div id="edit" style="width:700px;height:500px;margin:auto;border:2px solid gray;padding: 5px;overflow: auto;" contenteditable="true"> </div> <button id="save" style="width:300px;height:30px;margin:auto;margin-top:30px; background-color: green;border:1px solid green;display: block;color: white;font-family:'Courier New', Courier, monospace; font-weight: 500;font-size: 20px;">點 擊</button> <script> (function () { // 富文本編輯器類 class Editor { constructor() { this.bindElem(); } bindElem() { var toolbar = document.getElementById("toolbar"); var bs = toolbar.querySelectorAll('input,select'); for (var i = 0; i < bs.length; i++) { if (bs[i].tagName.toLowerCase() == 'select') { bs[i].onchange = function () { document.execCommand(this.name, true, this.value); } } else if (bs[i].tagName.toLowerCase() == 'input') { this.action(bs[i], bs[i].name); } } } action(obj, attr) { obj.onclick = function () { document.execCommand(attr,true); } } } new Editor(); document.getElementById("save").onclick = function(){ alert(document.getElementById("edit").innerHTML); } })(); </script> </body> </html>
知識點:html
1.contenteditable屬性編輯器
2.document.execCommand()方法ui
參考文章:this
1.http://www.javashuo.com/article/p-xzizccse-cc.htmlspa
參考資料:.net
1.https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommandcode