确定代码镜像是否滚动到底部

Determine if CodeMirror is scrolled to bottom

本文关键字:滚动 底部 是否 镜像 代码      更新时间:2023-09-26

我正在使用CodeMirror构建一个实时预览编辑器。我需要确定 CodeMirror 编辑器是否滚动到最底部,以便我也可以将预览滚动到底部。

我如何确定这一点?

你需要 codeMirror 中的 scroller 元素,然后在 scroll 事件上绑定一个函数。

斯菲德尔

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

不得不对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());
}

在我的预览div上,这些数字并不相等,所以我做了<= 0。(2px关闭,也许是由于边框?