如何在滚动时将jQuery fadeIn添加到Angular应用程序中

How to add jQuery fadeIn on scroll to Angular application

本文关键字:添加 Angular 应用程序 fadeIn jQuery 滚动      更新时间:2023-09-26

让我在序言中说,我意识到这是一种可怕的做法。然而,在AngularJS项目中,是否可以使用jQuery在滚动中淡入图像

我工作的最后期限很紧,需要让这个Angular项目看起来更好。我现在没有时间用Angular的方式来做这件事,所以快速和肮脏就足够了。

我现在的位置:

我有一个控制器,LandingCtrl

angular.module('appName.controllers', [])
       .controller('LandingCtrl',  ['$scope', function($scope) {
}]);

我有一个视图,里面有一堆div,我想在用户到达它们时淡出。

单独使用jQuery,它将非常直接,如下所示:http://jsfiddle.net/tcloninger/e5qaD/

$(document).ready(function() {
    /* Every time the window is scrolled ... */
    $(window).scroll( function(){
        /* Check the location of each desired element */
        $('.hideme').each( function(i){
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            /* If the object is completely visible in the window, fade it it */
            if( bottom_of_window > bottom_of_object ){
                $(this).animate({'opacity':'1'},500);
            }
        }); 
    });
});

然而,当我试图在我的控制器中使用作用域为所讨论视图的jQuery函数时,我会遇到各种各样的问题。

有什么方法可以正确地做到这一点吗?

提前谢谢。

如果你要使用jquery,你可以(几乎)坚持指令中的内容:

angular
    .module('app', [])
    .directive('scrollContainer', scrollContainer)

function scrollContainer($window) {
    return {
        restrict: 'A',
        scope: true,
        link: function(scope, element, attrs) {
            angular.element($window).bind("scroll", function() {
                $('.hideme').each( function(i){
                    var bottom_of_object = $(this).offset().top + $(this).outerHeight();
                    var bottom_of_window = $(window).scrollTop() + $(window).height();
                    /* If the object is completely visible in the window, fade it it */
                    if( bottom_of_window > bottom_of_object ){
                        $(this).animate({'opacity':'1'},500);
                    }
               });
           });
        }
    }
}


<body ng-app="app">
    <div id='container' scroll-container>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div class="hideme">Fade In</div>
        <div class="hideme">Fade In</div>
        <div class="hideme">Fade In</div>
        <div class="hideme">Fade In</div>
        <div class="hideme">Fade In</div>
    </div>
</body>

Plunker似乎坏了,所以我在代码笔上贴了一个工作示例

http://codepen.io/anon/pen/GgBzPg