$anchorScrollProvider
ng模块中的服务
当被调用的时候,页面会滚动到与元素相关联的指定的hash
处,或者滚动到当前$location.hash()
处,是依照HTML5 spec的规则制定的。
它当然也会监听$location.hash()
并且无论锚点值何时变化,都会自动地滚动到相应的位置。当不需要它时,可以调用$anchorScrollProvider.disableAutoScrolling()
让它失效。
另外我们可以使用它的yOffset
属性来指定一个垂直滚动偏移量(既可以是定值也可以是动态值)。
依赖
$window
$location
$rootScope
用法
$anchorScroll([hash])
;
参数
属性
yOffset
为了使
yOffset
正确地工作,滚动必须是在文档的根节点,而不是子节点。
例子
html
<div id="scrollArea" ng-controller="ScrollController"><a ng-click="gotoBottom()">Go to bottom</a><a id="bottom"></a> You're at the bottom!</div>
javascript
angular.module('anchorScrollExample', []).controller('ScrollController', ['$scope', '$location', '$anchorScroll',function ($scope, $location, $anchorScroll) {$scope.gotoBottom = function() {// 将location.hash的值设置为// 你想要滚动到的元素的id$location.hash('bottom');// 调用 $anchorScroll()$anchorScroll();};}]);
css
#scrollArea {height: 280px;overflow: auto;}#bottom {display: block;margin-top: 2000px;}
下面的例子将说明如何使用一个垂直滚动偏移(指定了一个固定值)关于$anchorScroll.yOffset
的详情请看上方介绍
html
<div class="fixed-header" ng-controller="headerCtrl"><a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">Go to anchor {{x}}</a></div><div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">Anchor {{x}} of 5</div>
javascript
angular.module('anchorScrollOffsetExample', []).run(['$anchorScroll', function($anchorScroll) {$anchorScroll.yOffset = 50; // 总是滚动额外的50像素}]).controller('headerCtrl', ['$anchorScroll', '$location', '$scope',function ($anchorScroll, $location, $scope) {$scope.gotoAnchor = function(x) {var newHash = 'anchor' + x;if ($location.hash() !== newHash) {// 将$location.hash设置为`newHash` and// $anchorScroll也将自动滚到该处$location.hash('anchor' + x);} else {// 显式地调用 $anchorScroll()方法 ,// 因为 $location.hash 并没有改变$anchorScroll();}};}]);
css
body {padding-top: 50px;}.anchor {border: 2px dashed DarkOrchid;padding: 10px 10px 200px 10px;}.fixed-header {background-color: rgba(0, 0, 0, 0.2);height: 50px;position: fixed;top: 0; left: 0; right: 0;}.fixed-header > a {display: inline-block;margin: 5px 15px;}
本文由作者原创,翻译内容仍有欠佳之处,请大家多多指正。via 村里有个村长 /@西瓜橘子葡萄冰