0
我想要做的是将3个元素(可能是4/5/6,需要动态)垂直放置在容器中的位置:绝对位置。我知道这可以用一些CSS来实现,但不幸的是我必须在JavaScript中这样做,所以我需要一个可以计算容器+儿童高度的函数/算法,然后均匀地定位它们。javascript - 以编程方式计算元素之间的填充
所以这里有一个测试用例:
<div id="element_1" style="position:relative;display:block;width:400px;height:768px">
<div id="child_1" style="position:absolute;display:block;width:400px;height:105px"></div>
<div id="child_2" style="position:absolute;display:block;width:400px;height:105px"></div>
<div id="child_3" style="position:absolute;display:block;width:400px;height:105px"></div>
</div>
有3个孩子的105px,高度每(孩子的高度总是彼此相同,所以JavaScript的我卡在需要定位的3个元素均匀地填充相等垂直
我已经试过类似:
var container; // dom instance of element_1
var children = []; // contains dom instances of each of the children (child_1, child_2, etc)
var container_height = container.getBoundingClientRect().height; // container is css3 scalable, hence the rect
var children_height = children[0].getBoundingClientRect().height; // for example
var padding = (container_height - (children_height*layers.length))/layers.length;
for(var i=0;i<children.length;i++){
children[i].style.top = (padding*(i+1) + (i*children_height)) + 'px';
}
而且它的工作原理有点,但有很多额外的空间在t的底部他的容器,所以它不是晚上间隔。
有人可以帮我吗?
应该有之前的第一和后填充孩子的数量第三?你为什么把它们设定为绝对的? – epascarello
是的,所有的元素应该在容器内均匀分布,所以在第一个元素之前和最后一个之后填充。 – Joe
因此,总高度减去div的高度,然后除以4. – epascarello