AngularJS:使用$animate隐藏滚动中的元素
AngularJS: Hide element on scroll with $animate
我有以下指令:
angular.module('mymod').directive("hideOnScroll", function($animate, $document) {
return function(scope, element, attrs) {
$document.bind('scroll', function () {
if ($document.scrollTop() > 80) {
console.log("this is fired1")
$animate.addClass(element, "fade");
} else {
console.log("this is fired2")
$animate.removeClass(element, "fade");
}
});
};
});
在的某个时刻,我在日志中有两条"this is fired"消息
另外,我有以下动画服务:
angular.module('mymod').animation(".fade", function() {
console.log("this is never fired3")
return {
addClass: function(element, className) {
console.log("this is never fired4")
//TweenMax.to(element, 1, {opacity: 0});
},
removeClass: function(element, className) {
console.log("this is never fired5")
//TweenMax.to(element, 1, {opacity: 1});
}
};
});
它的控制台消息都没有被触发。完全(3、4和5)。我检查了它是否被添加到浏览器中,是的。我有ngAnimate作为依赖
这就是要素:
<div hide-on-scroll>Hello</div>
编辑:我可以在chrome的元素检查器中看到,在'$animate.addClass(element,"fade")'被激发后,div没有得到新的类
我错过了什么?
当由addEventListener()
或由jqLite/jQuery方法on
和bind
手动附加的事件处理程序执行时,您需要手动触发摘要循环,让Angular知道发生了变化。
您可以使用$apply
(例如ng-click
在内部使用):
$document.bind('scroll', function() {
scope.$apply(function() {
if ($document.scrollTop() > 80) {
console.log("this is fired1");
$animate.addClass(element, "fade");
} else {
console.log("this is fired2");
$animate.removeClass(element, "fade");
}
});
});
还要注意,当您将事件侦听器附加到文档时,您应该在作用域被破坏时手动删除它们:
var onScroll = function() {
scope.$apply(function() {
if ($document.scrollTop() > 80) {
console.log("this is fired1");
$animate.addClass(element, "fade");
} else {
console.log("this is fired2");
$animate.removeClass(element, "fade");
}
});
};
$document.bind('scroll', onScroll);
scope.$on('$destroy', function() {
$document.unbind('scroll', onScroll);
});
演示:http://plnkr.co/edit/wl0vujSnBcb24FHGQ4il?p=preview
相关文章:
- 使用webdriver io在可滚动元素内滚动
- 每次单击按钮时水平滚动元素
- 可滚动元素,如何在调整大小时更改顶部偏移量
- 如何使用javascript检测不可滚动元素中的滚动事件和方向
- 滚动元素的交叉溶解过渡
- 自动上下滚动元素
- 检测可滚动元素内的滚动位置
- 为滚动元素制作动画
- 如何自动滚动元素
- 使用鼠标滚轮滚动元素时传播的事件是什么
- 在鼠标滚动时使用 JQuery 水平滚动元素
- 在屏幕顶部附近滚动元素时触发的侦听器
- 如何在调整大小时更改滚动元素的行为?(HTML,CSS,JavaScript)
- 滚动元素上的Javascript触摸移动事件
- Poshy提示不随滚动元素移动
- 如何在JQuery中滚动元素
- jsPDFaddHTML获取滚动元素的全部内容
- 使用鼠标滚轮滚动页面时,避免滚动可滚动元素
- 滚动元素到视图中而不与页眉重叠
- 如何为自定义滚动元素添加限制