使用js更改段落中某个单词的颜色


$('#txtInput').keyup(function(){
var txtInput = $(this).val();
localStorage.setItem('inputData', txtInput);
var returnData = localStorage.getItem('inputData');
$('#txtInput').val(returnData);
var hasTest = returnData.includes("<h1>");
if(hasTest == true){

}
});

我正在使用js创建一个文本编辑器。这里我使用localStorage来存储数据和检索数据。我需要添加突出显示语法功能。

例如:如果从文本中找到"h1",请将"h1"着色为红色。我使用了"。includes((,它找到了单词,但我不知道如何更改找到的文本的颜色。我真的很感谢你的帮助

试试这个解决方案:

1.使用contenteditable元素而不是inputtextarea

<div id="txtInput" contenteditable></div>

原因是我们需要在这个输入区域内显示带有CSS的HTML。

2.使用高亮文本过滤结果

// get highlight text from string
const highlighten = (string, highlight) => {
string = stripHtml(string);
// add highlight
if (string.includes(highlight)) {
string = string.replaceAll(highlight, `<span style="color:red">${highlight}</span>`);
}
return string;
};

使用replaceAll设置高亮显示CSS。您可以看到stripHTML(),它用于在进行筛选之前清洗字符串。

3.处理keyup事件

// on keyup event
$('#txtInput').on('keyup', function(e) {
const $input = $(e.currentTarget);
// you can manage your localStorage data here
// ...
// filter the input
$input.html(highlighten($input.html(), 'h1'));
// set caret
setCaretAtTheEnd($input.get());
});

当我们用新结果替换#txtInput时,我们将丢失插入符号的位置,这就是为什么我们需要setCaretAtTheEnd()将插入符号设置回输入的末尾。

// https://stackoverflow.com/questions/822452/strip-html-from-text-javascript
function stripHtml(html) {
let tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
// https://stackoverflow.com/questions/6249095/how-to-set-the-caret-cursor-position-in-a-contenteditable-element-div
function setCaretAtTheEnd(el) {
var range = document.createRange()
var sel = window.getSelection()
const nodes = el[0].childNodes;
let offset = 0;
nodes.forEach((node, i) => {
offset = node.length || 1;
});

range.setStart(nodes[nodes.length - 1], offset)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
}
// get highlight text from string
const highlighten = (string, highlight) => {
string = stripHtml(string);
// add highlight
if (string.includes(highlight)) {
string = string.replaceAll(highlight, `<span style="color:red">${highlight}</span>`);
}
return string;
};
// on keyup event
$('#txtInput').on('keyup', function(e) {
const $input = $(e.currentTarget);
// you can manage your localStorage data here
// ...
// filter the input
$input.html(highlighten($input.html(), 'h1'));
// set caret
setCaretAtTheEnd($input.get());
});
#txtInput {
width: 400px;
height: 200px;
border: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="txtInput" contenteditable>
</div>

这应该为您完成:

if (hasTest == true) {
returnData = returnData.replace('<h1>', '<h1 style="color:red">')
$('#txtInput').val(returnData);      
}

最新更新