Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

angularjs - Changing css on scrolling Angular Style

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

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');
    }

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);
    });
});

Muchos gracias amigos!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }
  };
});

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...