我想将活动项目拆分为其父元素的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>
答案 0 :(得分:0)
问题是您在超时之外设置typeHeaderHeight
和halfHeight
变量的值,因此它总是在项目实际打开之前计算,因此计算中存在错误
尝试使其像
setTimeout(() => {
var typeHeaderHeight = $('.item-header').outerHeight();
var halfHeight = Math.round($('.items').outerHeight() / 2);
$('.item').css('height', typeHeaderHeight);
$('.item.active').css('height', halfHeight);
});
},500)
&#13;
还有一件事......我不建议使用vanilla JavaScript的setTimeout尝试使用$timeout
代替它