使用ui-router和Angularjs自动滚动到TOP

Mr.*_*rth 65 javascript angularjs angular-ui-router

我已经阅读了很多不同的问题,并没有给出任何解决方案似乎适合我的用例.我开始只是在我的所有链接上放置target ="_ top",但这实际上迫使我的应用重新加载哪些不起作用.我也看到有人说他们使用的是autoscroll ="true",但只有在我的ui-view中它才会起作用.

这个问题是在我的index.html文件中我修复了导航和其他静态元素,这些元素位于我的第一个ui-view之上.这意味着当我转到其他页面时,当页面加载超过这些元素时,我将丢失导航.我也试过把它放在身体上:

<body autoscroll="true">
</body>
Run Code Online (Sandbox Code Playgroud)

这似乎也没有做任何事情.所以问题是,如何确保新页面(ui-router的新路由更改)从页面顶部开始?谢谢!

Tay*_*Mac 148

如果您希望它始终滚动到0跨浏览器,请不要对autoscroll执行任何操作.把它放在你的运行块上:

$rootScope.$on('$stateChangeSuccess', function() {
   document.body.scrollTop = document.documentElement.scrollTop = 0;
});
Run Code Online (Sandbox Code Playgroud)

  • 效果很好.我建议的唯一改进是使用这样的`$ document`服务:`$ document [0] .body.scrollTop = $ document [0] .documentElement.scrollTop = 0;` (27认同)
  • 晚了,但喜欢它! (4认同)

mdi*_*kin 14

使用版本1.0.6,$stateChangeSuccess不推荐使用该事件以支持该$transitions服务.以下是我在每次状态更改时滚动到顶部的代码:

app.run(['$transitions', function ($transitions) {
    $transitions.onSuccess({}, function () {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
    })
}]);
Run Code Online (Sandbox Code Playgroud)

  • 这是最新的答案,接受的答案是指旧的uirouter发布. (2认同)

che*_*ard 12

我有完全相同的问题,路线更改固定导航栏,页面加载部分向下滚动页面.

我刚添加autoscroll="false"ui-view,像这样:

<div ui-view="main" autoscroll="false"></div>
Run Code Online (Sandbox Code Playgroud)

编辑

刚试过这个方法,有点脏兮兮,但它确实有效.导入角度服务$anchorScroll$location进入ui-router .state配置的相关控制器.然后使用$watchon ui-router $stateParams调用$location.hash('top');路由/状态更改.

https://docs.angularjs.org/api/ng/service/ $ anchorScroll

https://docs.angularjs.org/api/ng/service/ $ location #hash

.controller('myCtrl', function ($location, $anchorScroll, $scope, $stateParams) {

    $scope.$watchCollection('$stateParams', function() {
       $location.hash('top');
       $anchorScroll();
    });
});
Run Code Online (Sandbox Code Playgroud)