我正在将 angularJS 与 ngRoute 一起使用。当用户向下滚动然后更改路线时,新页面也会向下滚动。我读过有关使用 autoscroll="true"
和 ngView
属性的信息。但我的问题是,由于我的 HTML 结构,滚动容器不是我的ngView
。就我而言,它看起来是这样的:
<body>
<!-- main container allows overflow scrolling and should be scrolled to top -->
<main>
<!-- this container has no scrolling -->
<div ngView><!-- content comes here --></div>
</main>
</body>
这就是为什么我的 ngView
上的 autoscroll="true"
没有执行任何操作,因为没有任何内容可以滚动。应该滚动的是我的 ngView
上方的容器(在本例中为 main
)。
我怎样才能做到这一点?我更喜欢尽可能少/简单的 JS。当然,像 autoscroll 属性这样的 HTML 解决方案会很好。
最佳答案
我已经找到了一种方法来做到这一点。我创建了一个指令,每次更改路线时都会滚动到容器的顶部。我可以通过 $rootScope
中的 $routeChangeSuccess
事件收听此内容。 scrollTop()
函数是我正在使用的 jQuery 的一部分。
HTML:
<!-- scrollable content container -->
<main id="pageWrap" scroll-top-on-route-change>
<!-- non-scrollable page content, templates inserted by ngView -->
<div id="pageContent" ng-view></div>
</main>
JS:
app.directive("scrollTopOnRouteChange", [
"$rootScope",
function ($rootScope) {
return {
restrict: "A",
link : function ($scope, $element) {
$rootScope.$on("$routeChangeSuccess", function () {
$element.scrollTop(0);
});
}
};
}
]);
关于javascript - 路线更改后滚动到顶部(嵌套 div),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32003355/