我在 Angular JS 上度过了最初的几个小时,并尝试用它编写 SPA。但是,在更改路线时,滚动位置在更改路线后仍保持在当前位置。这意味着,如果有人读完第二页上的一半文本,则在切换到第二页后,此人将在第二页时最终位于页面中间。 (假设页面同样长。)
当我寻找解决方案时,我只发现人们要求相反,即他们不想在更改页面后更改滚动位置。然而,我什至未能重现这一点。我想知道 Angular JS 的开发是否领先于这,并且我查阅的资料已经过时了。
我创建了一个最小版本来演示我的问题(只需添加两个文件 sample1.html
和 sample2.html
以及随机内容即可使其工作。):
<!DOCTYPE html>
<html>
<head lang="en"><title>SPA sample</title></head>
<body data-ng-app="myApp">
<div style="position: fixed;">
<a href="#/">Main</a>
<a href="#/other">Tutorial</a>
</div>
<div data-ng-view=""></div>
<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-route.min.js"></script>
<script>
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'noOp',
templateUrl: 'sample1.html'
})
.when('/other', {
controller: 'noOp',
templateUrl: 'sample2.html'
})
.otherwise({redirectTo: '/'});
});
myApp.controller('noOp', function ($scope) { });
</script>
</body>
</html>
最佳答案
根据 ngView
documentation :
autoscroll(optional) string:
Whether ngView should call $anchorScroll to scroll the viewport after the view is updated.
因此,您所要做的就是更改 ng-view
调用以打开自动滚动,如下所示:
<div ng-view autoscroll></div>
关于angularjs - 如何在路线更改时重置滚动位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22779753/