原生JS实现简单富文本编辑器

时间:2024-03-02 22:51:44
<!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>

 

 

 知识点:

  1.contenteditable属性

  2.document.execCommand()方法

 

参考文章:

  1.https://blog.csdn.net/WU5229485/article/details/79692430

参考资料:

  1.https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand