【问题标题】:Using AngularJS $anchorScroll to scroll to another page's anchor tag使用 AngularJS $anchorScroll 滚动到另一个页面的锚标记
【发布时间】:2015-03-13 14:07:54
【问题描述】:

从我的 AngularJS 主页,我需要滚动到另一个页面中的锚标记。根据 url,这两个页面都作为部分 html 进入 ng-view 组件。在启动服务器时,主页被加载并从那里需要转到常见问题页面。我使用带有# 的普通href,但这并没有指向目标页面中的正确div。这是我尝试使用$anchorScroll

这里是控制器方法

	
$scope.scrollToFaq = function(id) {
   $location.path("/faq")
   $location.hash(id);
   $anchorScroll();
}

这是我在 home.html 中的使用方式

<a ng-click="scrollToFaq('HERE')" href="" class="link">Here</a>

但这不能正常工作。如果我直接加载常见问题页面,然后返回并单击主页上的锚链接,它可以工作。是否可以使用 `$anchorScroll

来做到这一点

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    尝试使用 Angular 的 $timeout 服务。

    $scope.scrollToFaq = function(id) {
     $location.path("/faq");
     $timeout(function(){
       $location.hash(id);
       $anchorScroll();
     }, delay);
    

    这里delay 将是您希望等待锚滚动发生的时间。我读过大约 300 毫秒 / 400 毫秒为人们工作。当我遇到这个问题时,我只需要在$timeout 中调用$anchorscroll。因此,请使用最适合您的情况。

    注意:我正在寻找不使用$timeout 的解决方案。找到后会更新。

    【讨论】:

    • 我有同样的问题,你能告诉我其他不使用 $timeout 的解决方案吗??
    【解决方案2】:

    听起来像是一个与历史相关的问题。如果 div 已经被加载,一旦它被立即找到。这个解决方案过去对我有用。也许是等待页面加载的想法。

    $scope.scrollToFaq = function(id) {
        $location.path("/faq");
        $(window).on("load", function(){       
           $location.hash(id);
           $anchorScroll();
        });
        };  
    

    【讨论】:

    • 试过这个,但不幸的是它不起作用。在这种情况下,在某处阅读 onLoad 在 Angular 中不起作用。
    • 啊,好吧,我的情况有点不同。向你的作用域添加一个函数来监视你的 URL 然后相应地滚动怎么样?
    【解决方案3】:

    遇到了同样的问题。但修复了它:) 想法是更改为 URL,等待半秒然后跳转到锚点。

    HTML:

    <a href="" ng-click="goToAnchor('/', 'links')">Links</a>
    

    控制器:

    angular.module('exampleApp').controller('NavbarCtrl', function ($scope, $location, $timeout, $anchorScroll) {
          $scope.goToAnchor = function(path, anchor){
              $location.path('/');
    
              $timeout(function() {
                 $anchorScroll(anchor);
              }, 500);
          };
    });
    

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 2022-11-13
      • 2013-11-08
      • 1970-01-01
      • 2015-05-28
      相关资源
      最近更新 更多