ScrollTo function in AngularJS

后端 未结 9 1886
梦如初夏
梦如初夏 2020-11-27 11:43

I\'m trying to get a quick nav to work correctly. It\'s floating on the side. When they click on a link, it takes them to that ID on the page. I\'m following this guide fro

9条回答
  •  误落风尘
    2020-11-27 12:03

    Here is a simple directive that will scroll to an element on click:

    myApp.directive('scrollOnClick', function() {
      return {
        restrict: 'A',
        link: function(scope, $elm) {
          $elm.on('click', function() {
            $("body").animate({scrollTop: $elm.offset().top}, "slow");
          });
        }
      }
    });
    

    Demo: http://plnkr.co/edit/yz1EHB8ad3C59N6PzdCD?p=preview

    For help creating directives, check out the videos at http://egghead.io, starting at #10 "first directive".

    edit: To make it scroll to a specific element specified by a href, just check attrs.href.

    myApp.directive('scrollOnClick', function() {
      return {
        restrict: 'A',
        link: function(scope, $elm, attrs) {
          var idToScroll = attrs.href;
          $elm.on('click', function() {
            var $target;
            if (idToScroll) {
              $target = $(idToScroll);
            } else {
              $target = $elm;
            }
            $("body").animate({scrollTop: $target.offset().top}, "slow");
          });
        }
      }
    });
    

    Then you could use it like this:

    to scroll to the element clicked. Or
    to scroll to element with the id.

提交回复
热议问题