【问题标题】:AngularJS call function when a div is scrolled within (x) pixels from bottom of screen当 div 从屏幕底部在 (x) 像素内滚动时,AngularJS 调用函数
【发布时间】:2013-12-25 12:48:48
【问题描述】:

我正在尝试使用这个AngularJS infinite-scroll 指令。这是来源:

angular.module('infiniteScroll', [])
    .directive('infiniteScroll', [ "$window", function ($window) {
        return {
            link:function (scope, element, attrs) {
                var offset = parseInt(attrs.threshold) || 0;
                var e = element[0];

                element.bind('scroll', function () {
                    if (scope.$eval(attrs.canLoad) && e.scrollTop + e.offsetHeight >= e.scrollHeight - offset) {
                        scope.$apply(attrs.infiniteScroll);
                    }
                });
            }
        };
    }]);

这似乎只适用于滚动框中包含的元素。 Here's a Plunker which demonstrates this.

但是,我希望能够将这个简单的指令应用于静态的 DOM 元素,当元素接近窗口滚动的底部时调用 scope.$apply(attrs.infiniteScroll)

关于如何修改指令以允许这样做的任何想法?我尝试将e.scrollTop 更改为window.scrollTop,但无济于事,不幸的是,这超出了我目前的技能水平。

【问题讨论】:

    标签: javascript html angularjs angularjs-directive infinite-scroll


    【解决方案1】:

    我不完全确定我的问题是否正确。如果你想要一个调用函数的指令,如果某个 DOM 元素接近整个窗口的可见区域,那么这样的指令怎么样:

    myApp.directive('scrollTrigger', function($window) {
        return {
            link : function(scope, element, attrs) {
                var offset = parseInt(attrs.threshold) || 0;
                var e = jQuery(element[0]);
                var doc = jQuery(document);
                angular.element(document).bind('scroll', function() {
                    if (doc.scrollTop() + $window.innerHeight + offset > e.offset().top) {
                        scope.$apply(attrs.scrollTrigger);
                    }
                });
            }
        };
    });
    

    在 HTML 中可见区域下方的某处使用此元素:

    <div scroll-trigger="scrollEventCallback()" threshold="100">Trigger element</div>
    

    函数scrollEventCallback() 被调用,如果它比文档的当前可见区域低100 像素或更少。请注意,我在此示例中使用了 jQuery,因此要使其正常工作,您还必须包含它。我希望这是你所要求的。

    【讨论】:

      猜你喜欢
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多