我想将活动项目拆分为其父元素的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>

最佳答案

问题是您要在超时时间之外设置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代替它

关于javascript - 将盒子拆分成其父对象的高度的50%,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43909548/

10-09 04:07