Javascript 如何在 AngularJS 中滚动到页面顶部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28871434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to scroll to top of the page in AngularJS?
提问by Farjad Hasan
I want to scroll to the top of the page after getting an ajax call response using angularjs. Basically, I am displaying alert messages on top of the page and I want to focus the alert message as the ajax response received.
我想在使用 angularjs 获得 ajax 调用响应后滚动到页面顶部。基本上,我在页面顶部显示警报消息,我想在收到 ajax 响应时关注警报消息。
Thanks
谢谢
回答by Alexander T.
You can use
您可以使用
$window.scrollTo(x, y);
where xis the pixel along the horizontal axis and yis the pixel along the vertical axis.
其中x是沿水平轴y的像素,是沿垂直轴的像素。
Scroll to top
$window.scrollTo(0, 0);Focus on element
$window.scrollTo(0, angular.element('put here your element').offsetTop);
滚动到顶部
$window.scrollTo(0, 0);专注于元素
$window.scrollTo(0, angular.element('put here your element').offsetTop);
Update:
更新:
Also you can use $anchorScroll
你也可以使用 $anchorScroll
回答by Muhammad Reda
You can use $anchorScroll.
您可以使用$anchorScroll.
Just inject $anchorScrollas a dependency, and call $anchorScroll()whenever you want to scroll to top.
只需$anchorScroll作为依赖项注入,并$anchorScroll()在您想要滚动到顶部时调用。
回答by Partha Sarathi Ghosh
Ideally we should do it from either controller or directive as per applicable.
Use $anchorScroll, $locationas dependency injection.
理想情况下,我们应该根据适用的情况从控制器或指令中执行此操作。使用$anchorScroll,$location作为依赖注入。
Then call this two method as
然后将这两个方法称为
$location.hash('scrollToDivID');
$anchorScroll();
Here scrollToDivIDis the id where you want to scroll.
这scrollToDivID是您要滚动的 id。
Assumed you want to navigate to a error message div as
假设您要导航到错误消息 div
<div id='scrollToDivID'>Your Error Message</div>
For more information please see this documentation
有关更多信息,请参阅此文档
回答by Ignacio Ara
Don't forget you can also use pure JavaScript to deal with this situation, using:
不要忘记你也可以使用纯 JavaScript 来处理这种情况,使用:
window.scrollTo(x-coord, y-coord);
回答by Ather Parvez
use: $anchorScroll();
用: $anchorScroll();
with $anchorScrollproperty
与$anchorScroll财产

