Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 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 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...