$anchorScroll angular锚点服务

angular锚点服务 $anchorScroll

 

普通的html页面中,我们会通过在url后面添加#elementId的方式,将页面显示定位到某个元素上,也就是所谓的锚点。 

但是在angular应用的页面上,页面路由的写法是#route/route,锚点会被当做一个页面路由解析过去,达不到定位的目的。angular提供了$anchorScroll用来提供锚点的功能。

用法:  $anchorScroll([hash])

当被调用的时候,页面会滚动到与元素相关联的指定的hash处,或者滚动到当前$location.hsh()处。

<div ng-controller="ScrollController">

  <a ng-click="gotoBottom()">Go to bottom</a>
  <a id="bottom"></a> You're at the bottom!

</div>
angular.module('anchorScrollExample', [])

.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  function ($scope, $location, $anchorScroll) {

    $scope.gotoBottom = function() {

      // 将location.hash的值设置为
      // 你想要滚动到的元素的id
      $location.hash('bottom');

      // 调用 $anchorScroll()
      $anchorScroll();

    };
  }]);

angular还提供了一种方式,用来获取路由 #后面的地址,用法:

$scope.$id;

 

jQuery也提供了锚点服务:

$('body,html').animate({ scrollTop: $('#bottom').offset().top }, 500);

 

posted @ 2018-05-07 17:15  LittleMoon  阅读(1012)  评论(0编辑  收藏  举报