$anchorScroll angular锚点服务

angular锚点服务 $anchorScrollhtml

 

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

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

用法:  $anchorScroll([hash])code

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

<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还提供了一种方式,用来获取路由 #后面的地址,用法:blog

$scope.$id;

 

jQuery也提供了锚点服务:element

$('body,html').animate({ scrollTop: $('#bottom').offset().top }, 500);
相关文章
相关标签/搜索