在滚动角度样式时更改 css [英] Changing css on scrolling Angular Style

查看:33
本文介绍了在滚动角度样式时更改 css的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户以角度方式滚动时更改 CSS 元素.

I want to change CSS elements while a user scrolls the angular way.

这是以 JQuery 方式工作的代码

here's the code working the JQuery way

$(window).scroll(function() {
    if ($(window).scrollTop() > 20 && $(window).scrollTop() < 600) {
        $('header, h1, a, div, span, ul, li, nav').css('height','-=10px');
    } else if ($(window).scrollTop() < 80) {
        $('header, h1, a, div, span, ul, li, nav').css('height','100px');
    }

我尝试使用以下代码执行 Angular 方式,但 $scope.scroll 似乎无法正确获取滚动数据.

I tried doing the Angular way with the following code, but the $scope.scroll seemed to be unable to properly pickup the scroll data.

forestboneApp.controller('MainCtrl', function($scope, $document) {
    $scope.scroll = $($document).scroll();
    $scope.$watch('scroll', function (newValue) {
        console.log(newValue);
    });
});

亲爱的朋友们!

推荐答案

请记住,在 Angular 中,DOM 访问应该发生在指令内部.这是一个简单的指令,它根据窗口的 scrollTop 设置一个变量.

Remember, in Angular, DOM access should happen from within directives. Here's a simple directive that sets a variable based on the scrollTop of the window.

app.directive('scrollPosition', function($window) {
  return {
    scope: {
      scroll: '=scrollPosition'
    },
    link: function(scope, element, attrs) {
      var windowEl = angular.element($window);
      var handler = function() {
        scope.scroll = windowEl.scrollTop();
      }
      windowEl.on('scroll', scope.$apply.bind(scope, handler));
      handler();
    }
  };
});

我不清楚您正在寻找什么最终结果,所以这里有一个简单的演示应用程序,如果窗口向下滚动超过 50 个像素,它会将元素的高度设置为 1px: http://jsfiddle.net/BinaryMuse/Z4VqP/

It's not apparent to me exactly what end result you're looking for, so here's a simple demo app that sets the height of an element to 1px if the window is scrolled down more than 50 pixels: http://jsfiddle.net/BinaryMuse/Z4VqP/

这篇关于在滚动角度样式时更改 css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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