滚动页面时如何隐藏元素? [英] How can I hide an element when the page is scrolled?

查看:101
本文介绍了滚动页面时如何隐藏元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我有些困惑.

我试图考虑来自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

任何想法都将不胜感激.

Any ideas would be greatly appreciated.

推荐答案

一个基本指令如下所示.一个关键点是您需要调用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆