将类切换绑定到窗口滚动事件

2024-01-21

当用户将浏览器窗口滚动到某个点以下时,我将切换 #page div 的类。

到目前为止我所做的工作正常:

http://jsfiddle.net/eTTZj/29/ http://jsfiddle.net/eTTZj/29/

<div ng-app="myApp" scroll id="page">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 element.addClass('min');
                 console.log('Scrolled below header.');
             } else {
                 element.removeClass('min');
                 console.log('Header is in view.');
             }
        });
    };
});

(当他们将窗口滚动到标题下方 100px 时,类就会切换)

虽然,如果我错了,请纠正我,但我觉得这不是使用 Angular 执行此操作的正确方法。

相反,我认为执行此操作的最佳方法是使用 ng-class 并在范围中存储布尔值。像这样的事情:

<div ng-app="myApp" scroll id="page" ng-class="{min: boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
                 console.log('Scrolled below header.');
             } else {
                 scope.boolChangeClass = false;
                 console.log('Header is in view.');
             }
        });
    };
});

虽然这不是动态的,但如果我在滚动回调中更改 range.boolChangeClass 的值,则 ng-class 不会更新。

所以我的问题是:当用户滚动到某个点以下时,如何最好使用 AngularJS 切换 #page 的类?


感谢 Flek 在评论中回答了我的问题:

http://jsfiddle.net/eTTZj/30/ http://jsfiddle.net/eTTZj/30/

<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
             } else {
                 scope.boolChangeClass = false;
             }
            scope.$apply();
        });
    };
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将类切换绑定到窗口滚动事件 的相关文章

随机推荐