目标:我使用codemirror作为编辑。我想要
问题:
的jsfiddle:https://codemirror.net/demo/search.html
码:
https://jsfiddle.net/bababalcksheep/p7xg1utn/30/
调用$(document).ready(function() {
//
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "text/html",
lineNumbers: true,
});
//
function search(val) {
var cursor = editor.getSearchCursor(val);
while (cursor.findNext()) {
editor.setSelection(cursor.from(), cursor.to());
console.log('found at line ', cursor.pos.from.line + 1);
}
}
//
$('#search').click(function(event) {
event.preventDefault();
search(/^alpha|^beta/);
});
//
});
一次只能突出显示一个连续的子字符串。相反,您可以使用setSelection
方法,传入markText和cursor.from()
以获取要突出显示的位置:
cursor.to()
$(document).ready(function() {
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "text/html",
lineNumbers: true,
});
function search(val) {
var cursor = editor.getSearchCursor(val);
while (cursor.findNext()) {
editor.markText(
cursor.from(),
cursor.to(),
{ className: 'highlight' }
);
}
}
//
$('#search').click(function(event) {
event.preventDefault();
search(/^alpha|^beta/);
});
});
.CodeMirror {
border-top: 1px solid black;
border-bottom: 1px solid black;
height: 200px;
}
.highlight {
color: orange;
}