如何在滚动时根据可见的内部div高度调整外部div高度

时间:2016-05-15 14:41:05

标签: html css angularjs

我有以下示例html。 Files变量是一个简单的整数数组,如[1,2,3,4,5,6]

<!doctype html>
<html ng-app="Application">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
    <!--<script src="../app.js"></script>
    <script src="../Controller/applicationCtrl.js"></script>-->

    <script>
      var app = angular.module('Application', []);
      var applicationCtrl = function ($scope) {
          $scope.files = [1,2,3,4,5,6];
          $scope.showAll = false;
       };

      app.controller('vm', applicationCtrl);
    </script>
    <style>
        .J1 {
            overflow-y: scroll;
            height: 70px;
        }
    </style>
</head>
<body ng-controller="vm">
    <div style="width: 100px;" ng-class="{'J1': (files.length > 3) && !showAll}">
        <div ng-repeat="file in files" style="border-width: 1px; border-style: solid;">
            <span>{{file}}</span>
            <input type="button" value="{{'btn' + file}}"></input>
        </div>
    </div>
    <br />
    <div>
    <a href ng-click="showAll = !showAll;">Show {{ showAll ? 'less':'more'}}</a>
    </div>
</body>
</html>

如果文件数组的长度大于3,则将溢出的css添加到div。但我也将div的高度设置为固定值。我想要做的是根据前3个div的高度设置div的高度,而不为其设置固定值。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

你可以试试这个。我添加了jquery CDN。你可以用原始的javascript做到这一点。

<!doctype html>
<html ng-app="Application">
<head>
    <title></title>
   <script src="https://code.jquery.com/jquery-2.2.3.min.js"   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="   crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
    <script>
  var app = angular.module('Application', []);
  var applicationCtrl = function ($scope) {
      $scope.files = [1,2,3,4,5,6];
     
     /* Set the parent div's height */
      $(function(){
          $('.J1').height($('.each-button').outerHeight() * 3);
      });
    
   };

  app.controller('vm', applicationCtrl);
</script>
    <style>
        .J1 {
            overflow-y: scroll;
        }
    </style>
</head>
<body ng-controller="vm">
    <div style="width: 100px;" class="J1">
      <!-- new class has been added -->       
      <div class="each-button" ng-repeat="file in files" style="border-width: 1px; border-style: solid;">
            <span>{{file}}</span>
            <input type="button" value="{{'btn' + file}}"></input>
        </div>
    </div>
    <br />
    <div>
        <a href>Show more</a>
    </div>
</body>
</html>