当用户在页面底部附近滚动时调用一个函数

call a function when user scrolls near bottom of page

本文关键字:调用 函数 一个 滚动 用户 底部      更新时间:2023-09-26

我有一个对象数组,但我不需要看到所有对象,我想创建一个InfiniteCroll,并每8个项目发出请求,我使用JQuery的问题是,该方法像8次一样调用函数,导致重复相同的元素。

这是我的方法:

$(function() {
    $(window).scroll(function() {
        if ($(window).scrollTop() > $(document).height() - $(window).height() - a_little_bit_before) {
            $scope.NextIncidents();
        }
    });
});

用这个我做我的http请求

$scope.newincidents = [];
$scope.NextIncidents = function() {
    var urlnext = $scope.nextincidents;
    if (!urlnext) {
        $("#infinite").prop("disabled", true);
    } else {
        $("#infinite").prop("disabled", false);
    }
    var mycookie = $cookieStore.get('Token');
    $http({
        method: 'GET',
        url: urlnext,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-Token': ''UsernameToken Token="' + mycookie + '"',
        },
    }).success(function(data, status) {
        $scope.newincidents = data._embedded.incidents;
        var nextLink = data._links.next;
        $scope.nextincidents = nextLink ? nextLink.href : null;
        for (var n in $scope.incidents) {
            var month = new Date($scope.newincidents[n].upload_date).getMonth();
            $scope.incidents.push($scope.newincidents[n]);
            $scope.loadIncidents();
        };
    }).error(function(data, status, headers, config) {
        return false;
    });
    $scope.loadIncidents();
};

当用户在底部时,我怎么能一次只调用一个函数呢。现在该函数可以工作,但是,重复对象

直接绑定到window.scroll或window.resize这样的事件从来都不是一个好主意,因为每个浏览器触发这些事件的方式不同。相反,您应该使用debounce/stettle方法,这将确保您的事件处理程序不会被不必要地调用。

Ben Alman为此编写了一个非常受欢迎的插件,但许多主要的JavaScript库也包括去抖动和节流的方法(下划线、lodash、angular等)。

http://benalman.com/projects/jquery-throttle-debounce-plugin/

以下是它的工作原理:

$(window).on('scroll', $.throttle(300, function(){
    // handle the event here
}));

此外,稍后您可能会偶然发现另一个问题……当涉及到DOM时,"无限"的概念实际上并不存在。您将达到浏览器崩溃的极限。解决此问题的典型方法称为"虚拟渲染",在该方法中,当向底部添加新项时,还可以从集合的开头移除项(反之亦然)。

为了向用户呈现他们仍在"滚动"的错觉,您通常会将外部容器的高度设置为一次呈现所有内容时的实际高度。这种方法意味着集合中的每个元素都有某种已知/可计算的高度。