当用户将浏览器窗口滚动到某个点以下时,我将切换 #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 的类?