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

时间:2012-05-13 21:19:30

标签: javascript jquery codemirror

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

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

谢谢!

5 个答案:

答案 0 :(得分:9)

这个应该有效:

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); 
} 

答案 1 :(得分:4)

这很简单。

初​​始化:

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

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

editor.getScrollInfo();

它返回一个JavaScript对象:

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

现在您可以使用以下方式设置设置编辑器滚动位置:

editor.scrollTo(left,top);

答案 2 :(得分:2)

初​​始化:

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);
}

答案 3 :(得分:2)

您需要https://codemirror.net/doc/manual.html#scrollIntoView

注意可选的margin参数,它应该做你想要的:

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

您的代码类似于:

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

答案 4 :(得分:0)

// First, find the position of the object:

var offset = $('#object_id').offset()['top'];

// Next, find the window height:

var wh = $(window).height();

// Find the location you want it to be at:

var position = offset - ( wh / 2 );

// Finally, `scrollTo` the element:

scrollTo(0, position);

这需要jQuery

相关问题