2012-05-13 68 views

回答

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

+1

您正在滾動整個窗口而不是CodeMirror編輯器的內容 - 它應該如何工作? –

4

這是非常簡單的。

初始化:

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

如果你想當前位置以後設置,您可以使用

editor.getScrollInfo(); 

它返回一個JavaScript對象:

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

現在你可以設置設置編輯器滾動位置使用:

editor.scrollTo(left,top); 
4

這一個應該工作:

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); 
} 
相關問題