滚动页面时如何隐藏元素? [英] How can I hide an element when the page is scrolled?
问题描述
好吧,我有点难住了.
我正在尝试考虑来自 jQuery 背景的角度方式.
I'm trying to think the angular way coming from a jQuery background.
问题:如果窗口没有滚动,我只想隐藏一个固定元素.如果有人向下滚动页面,我想隐藏该元素.
The problem: I'd just like to hide a fixed element if the window is not scrolled. If someone scrolls down the page I would like to hide the element.
我已尝试创建自定义指令,但由于滚动事件未触发,因此无法使其正常工作.我在想一个像下面这样的简单控制器,但它甚至没有运行.
I've tried creating a custom directive but I couldnt get it to work as the scroll events were not firing. I'm thinking a simple controller like below, but it doesnt even run.
控制器:
.controller('MyCtrl2', function($scope,appLoading, $location, $anchorScroll, $window ) {
angular.element($window).bind("scroll", function(e) {
console.log('scroll')
console.log(e.pageYOffset)
$scope.visible = false;
})
})
查看
<a ng-click="gotoTop()" class="scrollTop" ng-show="{{visible}}">TOP</a>
实时预览http://www.thewinetradition.com.au/new/#/portfolio
任何想法将不胜感激.
推荐答案
基本指令看起来像这样.一个关键点是您需要调用 scope.$apply()
因为滚动将在正常的 digest
循环之外运行.
A basic directive would look like this. One key point is you'll need to call scope.$apply()
since scroll will run outside of the normal digest
cycle.
app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
scope.visible = false;
scope.$apply();
});
};
});
我发现这个 jsfiddle 很好地展示了它http://jsfiddle.net/88TzF/
I found this jsfiddle which demonstrates it nicely http://jsfiddle.net/88TzF/
这篇关于滚动页面时如何隐藏元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!