我发现了一些不受欢迎的行为,至少对我来说,当路线改变时。 在本教程的第11步http://angular.github.io/angular-phonecat/step-11/app/#/phones 你可以看到电话列表。如果你滚动到底部,点击最新的一个,你可以看到滚动不是在顶部,而是在中间。
我在我的一个应用程序中也发现了这个,我想知道如何让它滚动到顶部。我可以手动来做,但我认为应该有其他优雅的方法来做这个,我不知道。
那么,当路线改变时,是否有一种优雅的方式可以滚动到顶部?
我发现了一些不受欢迎的行为,至少对我来说,当路线改变时。 在本教程的第11步http://angular.github.io/angular-phonecat/step-11/app/#/phones 你可以看到电话列表。如果你滚动到底部,点击最新的一个,你可以看到滚动不是在顶部,而是在中间。
我在我的一个应用程序中也发现了这个,我想知道如何让它滚动到顶部。我可以手动来做,但我认为应该有其他优雅的方法来做这个,我不知道。
那么,当路线改变时,是否有一种优雅的方式可以滚动到顶部?
当前回答
经过一两个小时的尝试,ui-view autoscroll=true, $stateChangeStart, $locationChangeStart, $uiViewScrollProvider.useAnchorScroll(), $提供('$uiViewScroll',…),和许多其他的组合,我不能得到滚动到新页面顶部的工作预期。
这最终对我来说是有效的。它捕获pushState和replaceState,只在新页面被导航到时更新滚动位置(后退/前进按钮保留它们的滚动位置):
.run(function($anchorScroll, $window) {
// hack to scroll to top when navigating to new URLS but not back/forward
var wrap = function(method) {
var orig = $window.window.history[method];
$window.window.history[method] = function() {
var retval = orig.apply(this, Array.prototype.slice.call(arguments));
$anchorScroll();
return retval;
};
};
wrap('pushState');
wrap('replaceState');
})
其他回答
简单解决方案:在主路模块中添加scrollPositionRestoration功能。 是这样的:
const routes: Routes = [
{
path: 'registration',
loadChildren: () => RegistrationModule
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes,{scrollPositionRestoration:'enabled'})
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
你可以使用这个javascript
$anchorScroll()
经过一两个小时的尝试,ui-view autoscroll=true, $stateChangeStart, $locationChangeStart, $uiViewScrollProvider.useAnchorScroll(), $提供('$uiViewScroll',…),和许多其他的组合,我不能得到滚动到新页面顶部的工作预期。
这最终对我来说是有效的。它捕获pushState和replaceState,只在新页面被导航到时更新滚动位置(后退/前进按钮保留它们的滚动位置):
.run(function($anchorScroll, $window) {
// hack to scroll to top when navigating to new URLS but not back/forward
var wrap = function(method) {
var orig = $window.window.history[method];
$window.window.history[method] = function() {
var retval = orig.apply(this, Array.prototype.slice.call(arguments));
$anchorScroll();
return retval;
};
};
wrap('pushState');
wrap('replaceState');
})
供任何遇到标题中描述的问题的人参考(就像我一样),谁也在使用 AngularUI路由器插件…
在这个SO问题中,当你改变路由时,angular-ui路由器会跳到页面的底部。 不明白为什么页面在底部加载?Angular UI-Router自动滚动问题
然而,正如答案所述,你可以通过在ui视图中输入autoscroll="false"来关闭这种行为。
例如:
<div ui-view="pagecontent" autoscroll="false"></div>
<div ui-view="sidebar" autoscroll="false"></div>
http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-view
使用angularjs的UI路由器,我所做的是:
.state('myState', {
url: '/myState',
templateUrl: 'app/views/myState.html',
onEnter: scrollContent
})
:
var scrollContent = function() {
// Your favorite scroll method here
};
它在任何页面上都不会失败,而且它不是全局的。