js 使用contenteditable属性模拟富文本框 实现具体关键字高亮

问题是这样的,一般情况下,html的所有输入框是无法使某些关键字高亮的,所以我想使用div 的contenteditable属性作为编辑框,我们现在要给运维平台做一个sql在线查询工具,当运维输入sql 后,在输入框使指定关键字高亮,比如
select * from t_student 此处的 “select” 和“from” 要变成蓝色,当把“from” 删除掉一个单词后,要把高亮去掉

img

这里提供的主要是方法和思路【js富文本编辑器实现(快速了解JavaScript富文本编辑)】,链接:http://www.webzuan.cn/szk/7902.html

js方法实现过程

    function showYuqingDetailInfo(id){
        $.post("<%=basePath%>/yuQing/getYuQingInfo",{
            "id":id},
            function(data){
                 $('#fm').form('load',data);
                 var fyqXwContent = data.fyqXwContent;
                 document.getElementById("fyqYwDom").href=data.fyqYwDom;
                 $('#fyqYwDomfont').html(data.fyqYwDom);
                 
                 var fyqYqElement = data.fyqYqElement;//舆情要素
                 var entname = data.entname;//企业名称
                 var lastReplace = fyqXwContent;
                 
                 if(entname!= null&&entname.trim()!=""){
                     if(lastReplace.indexOf(entname)>0){
                         lastReplace = lastReplace.replace(eval("/"+entname+"/g"),"<span style='background-color: yellow;color:red'>"+entname+"</span>");
                     }
                     editor.html(lastReplace);
                 }
                 
                 if(fyqYqElement!=null&&fyqYqElement.trim()!=""){
                     if(fyqYqElement.indexOf(",") > 0){
                         var strs = fyqYqElement.split(",");
                         for(var i = 0; i < strs.length; i++){
                             lastReplace=lastReplace.replace(eval("/"+strs[i]+"/g"),"<span style='background-color: yellow;color:red'>"+strs[i]+"</span>");
                         }
                     } else{
                         lastReplace = lastReplace.replace(eval("/"+fyqYqElement+"/g"),"<span style='background-color: yellow;color:red'>"+fyqYqElement+"</span>");
                     }
                     editor.html(lastReplace);
                 }
                 
                 if((fyqYqElement==null||fyqYqElement.trim()=="")&&(entname==null||entname.trim()=="")){
                     editor.html(fyqXwContent);
                 }
        })
 
    }

https://blog.csdn.net/bjlf_1989/article/details/48135327

为什么不考虑vue-codemirror,感觉基本能满足使用需求吧,示例

img

可以使用highlight.js插件
每次编辑内容修改后,都触发highlight插件再次高亮关键字
对于百度富文本编辑器,增加我写的insetcode插件就可实现高亮关键字

// #highlight#
UE.parse.register("insertcode", function (utils) {
    let _document = this.root.querySelector('iframe').contentDocument
    let _window = this.root.querySelector('iframe').contentWindow
    var pres = _document.getElementsByTagName("pre");
    if (pres.length) {
        if (!_window.hljs) {
            var jsurl, cssurl;
            if (this.rootPath !== undefined) {
                jsurl = utils.removeLastbs(this.rootPath) + "/third-party/highlight/highlight.min.js"; // 高亮脚本
                cssurl = utils.removeLastbs(this.rootPath) + "/third-party/highlight/styles/tomorrow-night-bright.min.css"; // 样式文件,这里可以修改成自己喜欢的主题样式
            } else {
                jsurl = this.highlightJsUrl;
                cssurl = this.highlightCssUrl;
            }
            utils.loadFile(_document, {
                id: "highlight_css",
                tag: "link",
                rel: "stylesheet",
                type: "text/css",
                href: cssurl
            });
            utils.loadFile(
                _document, {
                    id: "highlight_js",
                    src: jsurl,
                    tag: "script",
                    type: "text/javascript",
                    defer: "defer"
                },
                function () {
                    // _window.hljs.highlightAll();
                    utils.each(pres, function (pi) {
                        _window.hljs.highlightElement(pi.querySelector('code'));
                    });
                }
            );
        } else {
            // utils.each(pres, function (pi) {
            //     if (pi.querySelector('code') && pi.querySelector('code').className.indexOf('hljs') < 0) {
            //         _window.hljs.highlightElement(pi.querySelector('code'));
            //     }
            // });
            utils.each(pres, function (pi) {
                // console.log(_window.hljs.highlight(pi.querySelector('code').innerText, { language: 'java' }).value)
                console.log(_window.hljs.highlight(pi.querySelector('code').innerText, { language: 'java' }).value)
                pi.querySelector('code').innerHTML = _window.hljs.highlight(pi.querySelector('code').innerText, { language: 'java' }).value
                // if (pi.querySelector('code') && pi.querySelector('code').className.indexOf('hljs') < 0) {
                //     _window.hljs.highlightElement(pi.querySelector('code'));
                // }
            });
        }
    }
});




<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    #odiv{
        border: 1px solid #ccc;
        height: 300px;
    }
</style>

<body>
    <div id="odiv" contenteditable>

    </div>
    <script>
        let odiv = document.getElementById('odiv');
        let timer;
        odiv.oninput = function (e) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                let str = e.target.innerHTML;
                let newStr = "";
        
                newStr = str.replace(/FROM/g, function (val) {
                    console.log(val, '===123')
                    return `<span contenteditable="false" style='color:#6795b5'>FROM</span>` + val.replace('FROM', '')
                });
                newStr = str.replace(/from/g, function (val) {
                    console.log(val, '===123')
                    return `<span contenteditable="false" style='color:#6795b5'>from</span>` + val.replace('from', '')
                });


                
                newStr = newStr.replace(/SELECT/g, function (val) {
                    console.log(val, '===123')
                    return `<span contenteditable="false" style='color:#6795b5'>SELECT</span>` + val.replace('SELECT', '')
                });
                newStr = newStr.replace(/selet/g, function (val) {
                    console.log(val, '===123')
                    return `<span contenteditable="false" style='color:#6795b5'>selet</span>` + val.replace('selet', '')
                });
                 
                this.innerHTML = newStr;
                getSelectPos('odiv')

            }, 800)

        }


        function getSelectPos(obj) {

            var esrc = document.getElementById(obj);

            var range = document.createRange();

            range.selectNodeContents(esrc);

            range.collapse(false);

            var sel = window.getSelection();

            sel.removeAllRanges();

            sel.addRange(range);

        }






    </script>
</body>

</html>