我突出顯示了CodeMirror中的HTML代碼行,並且我想添加一個將CodeMirror編輯器滾動到給定行的錨點。CodeMirror - 是否可以滾動到一行以使其位於窗口中間?
我可以通過setCursor方法滾動到第X行。但我想在CodeMirror窗口的中間有X行。我可以這樣做嗎?我研究了API和演示,但沒有運氣。
謝謝!
我突出顯示了CodeMirror中的HTML代碼行,並且我想添加一個將CodeMirror編輯器滾動到給定行的錨點。CodeMirror - 是否可以滾動到一行以使其位於窗口中間?
我可以通過setCursor方法滾動到第X行。但我想在CodeMirror窗口的中間有X行。我可以這樣做嗎?我研究了API和演示,但沒有運氣。
謝謝!
初始化:
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);
}
// 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的
您正在滾動整個窗口而不是CodeMirror編輯器的內容 - 它應該如何工作? –
這是非常簡單的。
初始化:
var editor = CodeMirror.fromTextArea(...);
如果你想當前位置以後設置,您可以使用
editor.getScrollInfo();
它返回一個JavaScript對象:
{
"left": 0,
"top": 0,
"height": 500,
"width": 500,
"clientHeight": 300,
"clientWidth": 200
}
現在你可以設置設置編輯器滾動位置使用:
editor.scrollTo(left,top);
這一個應該工作:
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);
}
你想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)
它適合你嗎? – PitaJ