当用户滚动到页面底部附近时调用函数

call a function when user scrolls near bottom of page

我有一个对象数组,但我不需要查看所有对象,我想创建一个 InfiniteScroll 并为每 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/throttle 方法,这将保证您的事件处理程序不会被不必要地调用。

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

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

工作原理如下:

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

此外,您稍后可能会偶然发现另一个陷阱... "infinite" 的概念在涉及 DOM 时确实不存在。您将达到可能导致浏览器崩溃的极限。解决此问题的典型方法称为 "virtual rendering",其中在将新项目添加到底部时,您还 从集合的开头删除 项(反之亦然) ).

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