绑定类切换到窗口滚动事件 [英] Bind class toggle to window scroll event
问题描述
当用户滚动低于某一点自己的浏览器窗口,我拨动类#page股利。
When a user scrolls their browser window below a certain point, I am toggling the class of the #page div.
我迄今所做的工作正常:
What I have done so far works fine:
<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.');
}
});
};
});
(当他们滚动头,100像素低于其窗口,该类切换)
(when they scroll their window below the header, 100px, the class is toggled)
虽然,纠正我,如果我错了,我觉得这是不是与角度做这种正确的方法。
Although, correct me if I'm wrong, I feel that this is not the correct way to be doing this with Angular.
相反,我presumed是这样做的最好的方法是用纳克级和存储范围的布尔值。事情是这样的:
Instead, I presumed that the best method for doing this would be by using ng-class and storing a boolean value in the scope. Something like this:
<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-类不更新。
Although this is not dynamic, if I change the value of scope.boolChangeClass in the scroll callback, then the ng-class is not updating.
所以我的问题是:如何最好切换类#page,采用AngularJS,当低于某个点用户滚动
So my question is: how is best to toggle the class of #page, using AngularJS, when the user scrolls below a certain point?
推荐答案
感谢Flek回答我的问题在他的评论:
Thanks to Flek for answering my question in his comment:
<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();
});
};
});
这篇关于绑定类切换到窗口滚动事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!