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

Mar*_*cka 8 javascript jquery codemirror

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

我可以通过setCursor方法滚动到第X行.但是我想在CodeMirror窗口中间放置X行.我能这样做吗?我研究了API和演示,但没有运气.

谢谢!

小智 10

这应该工作:

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); 
} 
Run Code Online (Sandbox Code Playgroud)


Rag*_*dra 5

这很简单。

在里面:

var editor = CodeMirror.fromTextArea(...);
Run Code Online (Sandbox Code Playgroud)

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

editor.getScrollInfo();
Run Code Online (Sandbox Code Playgroud)

它返回一个JavaScript对象:

{
  "left": 0,
  "top": 0,
  "height": 500,
  "width": 500,
  "clientHeight": 300,
  "clientWidth": 200
} 
Run Code Online (Sandbox Code Playgroud)

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

editor.scrollTo(left,top);
Run Code Online (Sandbox Code Playgroud)


Mar*_*cka 2

初始化:

var editor = CodeMirror.fromTextArea(...);
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)