当用户将浏览器窗口滚动到某个点以下时,我正在切换#page div 的类。
到目前为止我所做的工作正常:
<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.');
}
});
};
});
虽然这不是动态的,但如果我在滚动回调中更改 scope.boolChangeClass 的值,那么 ng-class 不会更新。
所以我的问题是:当用户滚动到某个点以下时,如何最好地切换#page 的类,使用 AngularJS?