如何在内容可编辑元素上为特定单词上色? [英] How can I color specific words on content editable element?

查看:0
本文介绍了如何在内容可编辑元素上为特定单词上色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个编码编辑器,我的问题是我想要在内容可编辑的div上为特定的单词上色,例如,如果用户编写了以下代码: function print(){}; function load(){};"函数"一词应涂成红色。

以下是我尝试过的方法,不幸的是它不起作用,但我想展示我的努力和我正在努力实现的想法。

let editor = document.getElementById("editor");

editor.oninput = () => {
    editor.innerHTML = colorWord(editor.innerHTML, "function");
    caretAtEnd(editor);
}

function colorWord(text, word) {
    while (text.includes(word)) {
        text = text.replace(word, "<span style='color:blue;'>" + word + "</span>");
    }
    return text;
}

function caretAtEnd(element) {
    element.focus();
    if (typeof window.getSelection != "undefined" &&
        typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(element);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(element);
        textRange.collapse(false);
        textRange.select();
    }
}

推荐答案

您的问题出在while循环。如果Word在文本中,则文本将始终包括word(因为您只是添加到字符串中),并且while循环将永远不会结束。只需将其更改为if

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
function colorWord(text, word) {
    if (text.includes(word)) {
        text = text.replace(word, "<span style='color:blue;'>" + word + "</span>");
    }
    return text;
}

这篇关于如何在内容可编辑元素上为特定单词上色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆