如何检测 Bootstrap 模态滚动条的位置?

How to detect position of the Bootstrap modal scrollbar?

我正在使用 JQuery 和 Bootstrap 并且我正在使用 ajax 请求加载模态,因此内容将在模态内部动态加载。

我设法通过单击按钮(也在模式内部)加载了更多内容,但我想实现 infinite scroll 功能。

但是 window.onscroll 函数似乎无法工作或无法识别模态内的滚动位置,即使我在第一个 ajax 请求后在模态内定义它也是如此。

问题:如何检测模态框内的特定元素是否对用户可见以自动加载更多内容?

这应该可以解决问题

const $modal = $("#myModal")
const $bookList = $modal.find('.media-list')

$modal.scroll(e => {
  const $middleBook = $bookList.find('.media').eq(BOOKS_CHUNK_SIZE / 2)
  const middleBookInViewport = $(window).height() > $middleBook.offset().top;

  if(bookChunks.length && middleBookInViewport){
    $bookList.append(bookChunks.shift().map(bookTemplate))
  }
})

jsFiddle

其实我自己找到了正确答案:

var modal_scrollTop = $('.modal-body').scrollTop();
var modal_scrollHeight = $('.modal-body').prop('scrollHeight');
var modal_innerHeight = $('.modal-body').innerHeight();

$('.modal-body').scroll(function() {

    // Write to console log to debug:
    console.warn('modal_scrollTop: ' + modal_scrollTop);
    console.warn('modal_innerHeight: ' + modal_innerHeight);
    console.warn('modal_scrollHeight: ' + modal_scrollHeight);

    // Bottom reached:
    if (modal_scrollTop + modal_innerHeight >= (modal_scrollHeight - 100)) {
        alert('reached bottom');
    } 

});

这将适用于 Bootstrap 4.7,它会从模态主体底部的底部触发控制台日志命令 100px。

$('.modal-body').bind('scroll', chk_scroll);

function chk_scroll(e) {
    var elem = $(e.currentTarget), offsetHeight = 100;

    if (elem[0].scrollHeight - elem.scrollTop() - elem.outerHeight() <= offsetHeight) {
        console.log('Near the bottom')
    }
}