javascript AngularJS。如何禁用自动滚动到我的页面顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14530572/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:52:43  来源:igfitidea点击:

AngularJS. How to disable auto-scroll to top of my page

javascriptangularjs

提问by Paul Kononenko

Tell me please, how can I disable auto-upto top of my page? If I use hash nav:

请告诉我,如何禁用自动升至我的页面顶部?如果我使用哈希导航:

<a href="#/index">Goto index</a>

my page doest up to top, but if I use AngularJS: Html:

我的页面没有达到顶部,但如果我使用 AngularJS:Html:

<a ng-href="#/index">Goto index</a>

JS:

JS:

$routeProvider.
      when('/index', {
          template:'...',
          controller: 'RouteCtrl'
      })

my page scrolled to top. How can I disable it?

我的页面滚动到顶部。我怎样才能禁用它?

回答by Jawa

I find it a bit strange that your plain hrefdoesn't scroll and ng-hrefscrolls, I thought it was the other way round...

我觉得你的平原href不滚动和ng-href滚动有点奇怪,我以为是相反的......

But, to the solution; It's up to the browser to scroll on hash changes, so usually to disable it you need to intercept and preventDefault()the event and then change the location by yourself. When using Angular, you can either define some attribute directive for the <a>element or just define your own adirective.

但是,对于解决方案;滚动哈希更改取决于浏览器,因此通常要禁用它,您需要拦截preventDefault()事件,然后自己更改位置。使用 Angular 时,您可以为<a>元素定义一些属性指令,也可以定义您自己的a指令。

If you use ng-view, it relies on $anchorScrollservice with view updates to simulate the behaviour what the browser would normally do, as Angular already intercepts the event. You can prevent the scroll on view load by providing your own $anchorScrollwhich does nothing:

如果您使用ng-view,它依赖$anchorScroll具有视图更新的服务来模拟浏览器通常会执行的行为,因为 Angular 已经拦截了该事件。您可以通过提供自己的$anchorScroll什么都不做来防止视图加载滚动:

angular.module('yourModule', []).value('$anchorScroll', angular.noop);

回答by Spain Train

As indicated in the AngularJS documentation, the proper way to do this is:

AngularJS 文档中所述,正确的方法是:

angular.module('yourModule',[]).config( ['$anchorScrollProvider', 
    function($anchorScrollProvider) {
        $anchorScrollProvider.disableAutoScrolling();
    }]
);

回答by IHadzera

just try

你试一试

assessmentApp.run(['$anchorScroll', function($anchorScroll) {
    $anchorScroll = angular.noop;
}])