CodeMirror是一个功能强大的JavaScript代码编辑器,它支持通过正则表达式实现文本高亮显示。本文将详细介绍实现这一功能的完整方法。
首先确保你已经引入了CodeMirror库:
<link rel="stylesheet" href="codemirror.css">
<script src="codemirror.js"></script>
1. 创建CodeMirror实例:
var editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
mode: "text/plain",
lineNumbers: true
});
2. 使用正则表达式高亮:
editor.markText(
{line: 0, ch: 0}, // 起始位置
{line: 0, ch: 10}, // 结束位置
{className: "highlight"} // CSS类名
);
要使用正则表达式高亮所有匹配的文本:
function highlightRegex(regex, className) {
var cursor = editor.getSearchCursor(regex);
while (cursor.findNext()) {
editor.markText(
cursor.from(),
cursor.to(),
{className: className}
);
}
}
实现实时高亮用户输入的正则表达式:
document.getElementById("highlight-btn").addEventListener("click", function() {
var regex = new RegExp(document.getElementById("regex-input").value, "g");
highlightRegex(regex, "custom-highlight");
});
别忘了为高亮文本添加CSS样式:
.highlight {
background-color: yellow;
font-weight: bold;
}
.custom-highlight {
background-color: #ffcccc;
border: 1px solid #ff9999;
}
addOverlay方法实现持续高亮lineClass高亮整行bookmark实现可点击的高亮标记通过以上方法,你可以灵活地在CodeMirror编辑器中实现各种正则表达式高亮效果,满足不同的代码编辑需求。