【问题标题】:AngularJS $anchorScroll yOffset within a child element子元素内的AngularJS $anchorScroll yOffset
【发布时间】:2015-05-30 20:38:29
【问题描述】:

据我了解 $anchorScroll yOffset 在子元素中是不可能的: “为了使 yOffset 正常工作,滚动应该在文档的根而不是某个子元素上进行。” https://docs.angularjs.org/api/ng/service/$anchorScroll

示例(根据 AngularJS 文档修改): 我想点击一个链接并在滚动到的内容上方添加“介于”一词。

index.html

<body ng-app="anchorScrollOffsetExample">
    <div class="fixed-header" ng-controller="headerCtrl">
    <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
      Go to inner-anchor {{x}}
    </a>
  </div>
  <div id="anchor" class="anchor">
    <div ng-repeat="x in [1,2,3,4,5]">
        between
        <div id="innerAnchor{{x}}" class="anchor" >Inner-Anchor {{x}} of 5</div>
    </div>
  </div>
</body>

style.css

  .anchor {
    border: 2px dashed DarkOrchid;
    padding: 10px 10px 200px 10px;
    max-height:500px;
    overflow-y: auto;
  }

script.js

angular.module('anchorScrollOffsetExample', [])
.run(['$anchorScroll', function($anchorScroll) {
  $anchorScroll.yOffset = 500;
}])
.controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  function ($anchorScroll, $location, $scope) {
    $scope.gotoAnchor = function(x) {
      var newHash = 'anchor' + x;
      if ($location.hash() !== newHash) {
        $location.hash('innerAnchor' + x);
      } else {
        $anchorScroll();
      }
    };
  }
]);

http://plnkr.co/edit/yFj9fL3sOhDqjhMawI72?p=preview

在 AngularJS(最好没有 jQuery 或其他库)中是否有一种好方法可以做到这一点,而无需将“之间”移动到我正在滚动到的 DIV 内部?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    为什么不用锚标签?

    <body ng-app="anchorScrollOffsetExample">
        <div class="fixed-header" ng-controller="headerCtrl">
        <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
          Go to inner-anchor {{x}}
        </a>
      </div>
      <div id="anchor" class="anchor">
        <div ng-repeat="x in [1,2,3,4,5]">
            <!-- Add an anchor above the text, and we scroll here instead of the div -->
            <a name="innerAnchor{{x}}"></a>
            between
            <div class="anchor" >Inner-Anchor {{x}} of 5</div>
        </div>
      </div>
    </body>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 2014-12-16
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多