简体   繁体   English

确定CodeMirror是否滚动到底部

[英]Determine if CodeMirror is scrolled to bottom

I'm building a live-preview editor with CodeMirror . 我正在使用CodeMirror构建实时预览编辑器。 I need to determine if the CodeMirror editor is scrolled to the very bottom so that I can scroll the preview to the bottom as well. 我需要确定CodeMirror编辑器是否滚动到最底端,以便我也可以将预览滚动到最底端。

How can I determine this? 我该如何确定?

You need the scroller element in codeMirror, then bind a function on scroll event. 您需要codeMirror中的scroller元素,然后在scroll事件上绑定一个函数。

jsfiddle 的jsfiddle

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    mode: "text/html"
});    

var scrollElement = editor.getScrollerElement();
  console.log(scrollElement )
  $(scrollElement).bind('scroll', function(e) {
      var elem = $(e.currentTarget);
      if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
          console.log("bottom");
      }      
  });

Had to make some minor adjustments to aljordan82's solution: 必须对aljordan82的解决方案进行一些小的调整:

var editor = CodeMirror.fromTextArea(document.getElementById('post'), {
    'mode': 'gfm',
    'lineNumbers': true,
    'theme': 'default',
    'lineWrapping': true,
});

var $preview = $('#preview-div');
var $scroller = $(editor.getScrollerElement());

$.fn.scrollHeight = function() {
    return this[0].scrollHeight;
};

var atBottom = $scroller.scrollHeight() - $scroller.scrollTop() - $scroller.outerHeight() <= 0
    && $preview.scrollHeight() - $preview.scrollTop() - $preview.outerHeight() <= 0;
$preview.html(html);
if (atBottom) {
    $preview.scrollTop($preview.scrollHeight());
}

The numbers weren't coming out quite equal on my preview div, so I did <= 0 instead. 在预览div上得出的数字并不完全相等,所以我改为<= 0 (2px off, maybe due to borders?) (关闭2px,也许是由于边界?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM