2024年7月2日
关键词实时高亮
<style>
#tbox { width: 800px; height: 500px; border: 1px solid gray; padding: 10px; margin: 10px auto; position: relative; }
::highlight(kw-red) { color: red; }
</style>
<div id="tbox" contenteditable="plaintext-only" onmousemove="this.focus();">单价:0.99元</div>
<script>
//设定高亮颜色
const hlColor = new Highlight();
CSS.highlights.set('kw-red', hlColor);
//高亮函数
const hlight = (ele) => {
const reg = /[\d\.]/g;
const walker = document.createTreeWalker(tbox, NodeFilter.SHOW_TEXT);
while(walker.nextNode()) {
const textNode = walker.currentNode;
const text = textNode.textContent;
const res = text.matchAll(reg);
res.forEach(r => {
const range = new Range();
range.setStart(textNode, r['index']);
range.setEnd(textNode, r['index'] + r[0].length);
hlColor.add(range);
});
}
};
//富文本框输入事件 :实时高亮关键字
tbox.oninput = () => hlight(tbox);
//首次启动高亮
hlight(tbox);
</script>
|