首页 > 解决方案 > 单击按钮angularjs时的水平滚动条

问题描述

我正在尝试使用按钮获得水平滚动。我有一个容器,它有几个水平堆叠的元素(可以超过 3 个,从后端获取值),我想使用按钮滚动它们。我也想在没有滚动条时隐藏这些按钮。

标签: angularjs

解决方案


这是非常简单和有用的:

angular.module('anchorScrollOffsetExample', [])
.run(['$anchorScroll', function($anchorScroll) {
  $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels
}])
.controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  function($anchorScroll, $location, $scope) {
    $scope.gotoAnchor = function(x) {
      var newHash = 'anchor' + x;
      if ($location.hash() !== newHash) {
        // set the $location.hash to `newHash` and
        // $anchorScroll will automatically scroll to it
        $location.hash('anchor' + x);
      } else {
        // call $anchorScroll() explicitly,
        // since $location.hash hasn't changed
        $anchorScroll();
      }
    };
  }
]);
body {
  padding-top: 50px;
}

.anchor {
  border: 2px dashed DarkOrchid;
  padding: 10px 10px 200px 10px;
}

.fixed-header {
  background-color: rgba(0, 0, 0, 0.2);
  height: 50px;
  position: fixed;
  top: 0; left: 0; right: 0;
}

.fixed-header > a {
  display: inline-block;
  margin: 5px 15px;
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-anchor-scroll-offset-production</title>
  <link href="style.css" rel="stylesheet" type="text/css">
  

  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="script.js"></script>
  

  
</head>
<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 anchor {{x}}
  </a>
</div>
<div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  Anchor {{x}} of 5
</div>
</body>
</html>

  


推荐阅读