CodeMirror - 是否可以滚动到一行,使其位于窗口中间

CodeMirror - Is it possible to scroll to a line so that it is in the middle of window?

本文关键字:中间 窗口 于窗口 一行 是否 滚动 CodeMirror      更新时间:2023-09-26

我在 CodeMirror 中突出显示了 HTML 代码行,我想添加一个锚点,将 CodeMirror 编辑器滚动到给定行。

我可以通过 setCursor 方法滚动到第 X 行。但是我希望将X行放在CodeMirror窗口的中间。我能做到吗?我研究了 API 和演示,但没有运气。

谢谢!

这个应该可以工作:

var editor = CodeMirror.fromTextArea(...);
function jumpToLine(i) { 
    var t = editor.charCoords({line: i, ch: 0}, "local").top; 
    var middleHeight = editor.getScrollerElement().offsetHeight / 2; 
    editor.scrollTo(null, t - middleHeight - 5); 
} 

这很简单。

初始化:

var editor = CodeMirror.fromTextArea(...);

如果希望当前位置稍后设置,可以使用

editor.getScrollInfo();

它返回一个 JavaScript 对象:

{
  "left": 0,
  "top": 0,
  "height": 500,
  "width": 500,
  "clientHeight": 300,
  "clientWidth": 200
} 

现在,您可以使用以下命令设置设置编辑器滚动位置:

editor.scrollTo(left,top);

你想要 https://codemirror.net/doc/manual.html#scrollIntoView

请注意可选的边距参数,它应该执行您想要的操作:

cm.scrollIntoView(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)

您的代码如下所示:

cm.scrollIntoView({line:50, char:5}, 200)

初始化:

var editor = CodeMirror.fromTextArea(...);

在编辑器中间显示一行的函数:

function jumpToLine(i) {
    // editor.getLineHandle does not help as it does not return the reference of line.
    editor.setCursor(i);
    window.setTimeout(function() {
       editor.setLineClass(i, null, "center-me");
       var line = $('.CodeMirror-lines .center-me');
       var h = line.parent();
       $('.CodeMirror-scroll').scrollTop(0).scrollTop(line.offset().top - $('.CodeMirror-scroll').offset().top - Math.round($('.CodeMirror-scroll').height()/2));
   }, 200);
}