js编辑器插件

时间:2021-07-09 18:21:49

使用js实现一款简单的编辑器插件,可以实现文字的编辑,图片的上传操作。

/** * 自定义编辑器 * @param {Object} id 编辑区 * @param {Object} control 操作区 */
function insertImg(id, control, dataparams, fun){
    this.bigBox  = document.getElementById(id),
    this.handles = document.getElementById(control),
    this.handle  = this.handles.children[0],
    this.handleChildt  = this.handle.children[1],
    this.gethtml = this.handles.children[1],
    param = dataparams,
    funs = fun,
    this.init()
}
insertImg.prototype = {
    init:function(){

        this.edit();      //编辑操作
        this.getResult(); //编辑操作

    },
    pasteHandler:function() {
        var that = this;
        /** * 监控粘贴(ctrl+v),粘贴过来的替换多余的html代码,只保留<br> */
        setTimeout(function() {

            var content = that.innerHTML;
            valiHTML = ["br"];
            content = content.replace(/_moz_dirty=""/gi, "").replace(/\[/g, "[[-").replace(/\]/g, "-]]").replace(/<\/ ?tr[^>]*>/gi, "[br]").replace(/<\/ ?td[^>]*>/gi, "&nbsp;&nbsp;").replace(/<(ul|dl|ol)[^>]*>/gi, "[br]").replace(/<(li|dd)[^>]*>/gi, "[br]").replace(/<p [^>]*>/gi, "[br]").replace(new RegExp("<(/?(?:" + valiHTML.join("|") + ")[^>]*)>", "gi"), "[$1]").replace(new RegExp('<span([^>]*class="?at"?[^>]*)>', "gi"), "[span$1]").replace(/<[^>]*>/g, "").replace(/\[\[\-/g, "[").replace(/\-\]\]/g, "]").replace(new RegExp("\\[(/?(?:" + valiHTML.join("|") + "|img|span)[^\\]]*)\\]", "gi"), "<$1>");

            if(!$.browser.mozilla) {

                content = content.replace(/\r?\n/gi, "<br>");

            }

            that.innerHTML = content;
        }, 1)
    },
    _insertimg:function(str) {
        /* * 锁定编辑器中鼠标光标位置。 */
        var selection = window.getSelection ? window.getSelection() : document.selection;

        var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0);

        if(!window.getSelection) {

            this.bigBox.focus();

            var selection = window.getSelection ? window.getSelection() : document.selection;

            var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0);

            range.pasteHTML(str);

            range.collapse(false);

            range.select();

        } else {

            this.bigBox.focus();

            range.collapse(false);

            var hasR = range.createContextualFragment(str);

            var hasR_lastChild = hasR.lastChild;

            while(hasR_lastChild && hasR_lastChild.nodeName.toLowerCase() == "br" && hasR_lastChild.previousSibling && hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br") {

                var e = hasR_lastChild;

                hasR_lastChild = hasR_lastChild.previousSibling;

                hasR.removeChild(e)

            }

            range.insertNode(hasR);

            if(hasR_lastChild) {

                range.setEndAfter(hasR_lastChild);

                range.setStartAfter(hasR_lastChild)

            }

            selection.removeAllRanges();

            selection.addRange(range)

        }

    },
    enterkey:function() {
        /* * 监控按enter键和空格键,如果按了enter键,则取消原事件,用<BR/ >代替。 */
        e = event.keyCode;

        if(e == 13 || e == 32) {

            var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

            event.returnValue = false; // 取消此事件的默认操作 

            if(document.selection && document.selection.createRange) {

                var myRange = document.selection.createRange();

                myRange.pasteHTML('<br />');

            } else if(window.getSelection) {

                var selection = window.getSelection();

                var range = window.getSelection().getRangeAt(0);

                range.deleteContents();

                var newP = document.createElement('br');

                range.insertNode(newP);

            }

        }
    },
    edit:function() {
        var that = this;
        //复制粘贴以及回车换行操作
        this.bigBox.onkeydown = this.enterkey;
        this.bigBox.onpaste = this.pasteHandler;

        //上传图片
        this.handleChildt.onchange = function() {
            that.upLoadIMg();
        }
    },
    getResult:function() {
        //获取需要的结果
        var that = this;
        this.gethtml.onclick = function() {
            $(that.bigBox).find('br').remove(); //去除br 
            var html = that.bigBox.innerHTML;
            //正则修改img为自己想要的格式
            var reg = /<img src="(.*?)" dataUrl="(.*?)">/ig;
            //需要提交的内容
            param.content = html.replace(reg, '##@$2@##').replace(/\s/g, "");
            param.title = $.trim($('.titles').val())
            param.topicid = $('#topicid option:selected').val()
            $.post(param.saveData,param,function(data){
                var data = JSON.parse(data)
                if(data.code == '10000'){
                    //确认完回调
                    if(funs){
                        funs();
                    }
                }
            })
        }

    },
    upLoadIMg:function() {
        //插入图片
        var that = this;
        if(that.handleChildt.files[0] != undefined){
            //构造form表单上传 
            var as = new FormData();  
            as.append("uploadfile",that.handleChildt.files[0]); //参数uploadfile
            $.ajax({  
                url:param.upImgSrc,  
                xhrFields:{  
                    withCredentials:true  
                },
                type: "POST",  
                cache: false,  
                data: as,  
                processData: false,  
                contentType:false,
                success: function (result) {
                    alert(1)
                    var data = JSON.parse(result);
                    if(data.code == '10000'){  
                        that.bigBox.focus();
                        var img_url = '<img src="https://p5.gexing.com/'+data.data.url+'" dataUrl="'+data.data.url+'">';
                        that._insertimg(img_url);
                    }else{  
                        alert('上传失败!')  
                    }  
                }  
            })  
        }
    }
}
/** * [insertImgs 初始化编辑器] * @type {Object} editCont 编辑器 * @type {Object} handle 操作控制按钮 * @type {Object} params 参数 * @type {Object} function 成功后的回调函数 */
        var insertImgs = new insertImg('editCont','handle',params,function(){
            //保存成功后的事件

        });
<div id="editCont" contenteditable="true" class="editbox" style="width: 400px;height: 700px;border: 1px solid #ccc;padding:10px;float: left;overflow: auto;">
</div>
<div style="padding: 20px 16px;text-align:center;" id="handle">
            <form action="" id="add_file_form" class="loadImgBox" method="post" enctype="multipart/form-data">
                <span>上传图片</span>
                <input id="uploaderInput" class="weui-uploader__input" name="uploadfile" type="file" accept="image/jpeg,image/jpg,image/png" multiple="">  
            </form>
            <input class="btn j_btn" style="margin-left:50px;" type="button" name="submit" value="保存">
        </div>