[英]CodeMirror - Is it possible to scroll to a line so that it is in the middle of window?
I'm highlighting lines of HTML code in CodeMirror and I want to add an anchor that scroll CodeMirror editor to a given line. 我要在CodeMirror中突出显示HTML代码行,并想添加一个将CodeMirror编辑器滚动到给定行的锚点。
I can scroll to a line X via setCursor method. 我可以通过setCursor方法滚动到X行。 But I would like to have the line X in the middle of CodeMirror window. 但是我想在CodeMirror窗口的中间放置X行。 Can I do that? 我可以那样做吗? I studied the API and demos but with no luck. 我研究了API和演示,但没有运气。
Thanks! 谢谢!
This one should work: 这应该工作:
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);
}
It is very simple. 这很简单。
Init: 在里面:
var editor = CodeMirror.fromTextArea(...);
If you want current position to set it later, you can use 如果要稍后设置当前位置,可以使用
editor.getScrollInfo();
It returns an JavaScript object: 它返回一个JavaScript对象:
{
"left": 0,
"top": 0,
"height": 500,
"width": 500,
"clientHeight": 300,
"clientWidth": 200
}
now you can set set editor scroll position using: 现在,您可以使用以下命令设置编辑器滚动位置:
editor.scrollTo(left,top);
Initialization: 初始化:
var editor = CodeMirror.fromTextArea(...);
Function to show a line in the middle of editor: 在编辑器中间显示一行的功能:
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);
}
You want https://codemirror.net/doc/manual.html#scrollIntoView 您需要https://codemirror.net/doc/manual.html#scrollIntoView
Notice the optional margin parameter which should do what you want: 请注意可选的margin参数,它应该执行您想要的操作:
cm.scrollIntoView(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)
Your code would be something like: 您的代码将类似于:
cm.scrollIntoView({line:50, char:5}, 200)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.