如何检测引导模态滚动条的位置

How to detect position of the Bootstrap modal scrollbar?

本文关键字:模态 滚动条 位置 何检测 检测      更新时间:2023-09-26

我正在使用JQuery和Bootstrap,我正在加载一个ajax请求的模态,所以内容将在模态内动态加载。

我设法加载更多的内容与一个按钮点击(也在模态),但我想实现一个无限滚动功能。

然而,window.onscroll函数似乎没有工作或识别模态内的滚动位置,即使我在第一个ajax请求后在模态内定义它。

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

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

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

应该可以了

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

这将适用于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')
    }
}