【问题标题】:Splitting boxes to 50% height of their parent拆分框到其父级的 50% 高度
【发布时间】:2017-05-11 07:52:54
【问题描述】:

我想将活动项目拆分为其父元素的 50% 高度。因此,当我打开前两个项目时,它们应该拆分为父类.items 的 50%(两个 .item 都有 100px)。所以我可以在不滚动的情况下看到两者。同样,当我打开所有三个时,它们的高度应该是 100px,这是它们父级的一半。我的问题是,第二项重叠,我必须滚动。怎么了?

angular.module("myApp", []).controller("myController", function($scope) {
  $scope.itemList = [{
    id: 1,
    name: "Item 1",
    isOpen: false
  }, {
    id: 2,
    name: "Item 2",
    isOpen: false
  }, {
    id: 3,
    name: "Item 3",
    isOpen: false
  }];

  $scope.setHeight = function() {
    if ($scope.itemList.length > 1) {
      var typeHeaderHeight = $('.item-header').outerHeight();
      var halfHeight = Math.round($('.items').outerHeight() / 2);

      setTimeout(() => {
        $('.item').css('height', typeHeaderHeight);
        $('.item.active').css('height', halfHeight);
      });
    }
  }
});
.frame {
	display: flex;
	flex-direction: column;
	height: 200px;
}

.items {
  display: flex;
  flex: 1 1 auto;
  flex-direction: column;
  overflow: auto;
  border: 1px solid black;
}

.item {
  display: flex;
  flex-direction: column;
  flex: 0 0 auto;
  margin-bottom: 5px;
  background-color: rgb(150, 150, 150);
  color: white;
}

.item:hover {
  cursor: pointer;
}

.item-header {
  position: relative;
  display: flex;
}

.active {
  background-color: rgb(220, 220, 220);
  color: rgb(150, 150, 150);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div class="frame" ng-app="myApp" ng-controller="myController">
  <div class="items">
    <div class="item" ng-repeat="item in itemList" ng-click="item.isOpen = !item.isOpen; setHeight()" ng-class="{active: item.isOpen}">
      <div class="item-header">
        {{item.name}}
      </div>
    </div>
  </div>
</div>

【问题讨论】:

    标签: javascript jquery html css angularjs


    【解决方案1】:

    问题是您在超时之外设置了typeHeaderHeighthalfHeight 变量的值,所以它总是在项目实际打开之前计算,所以计算中有错误

    试着让它像

       
       
    
          setTimeout(() => {
          var typeHeaderHeight = $('.item-header').outerHeight();
          var halfHeight = Math.round($('.items').outerHeight() / 2);
         
            $('.item').css('height', typeHeaderHeight);
            $('.item.active').css('height', halfHeight);
          });
        },500)
          
       

    还有一件事.. 我不建议使用原生 JavaScript 的 setTimeout 尝试使用 $timeout 代替它

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      相关资源
      最近更新 更多