2017-09-26 71 views
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的底部他的容器,所以它不是晚上间隔。

有人可以帮我吗?

+0

应该有之前的第一和后填充孩子的数量第三?你为什么把它们设定为绝对的? – epascarello

+0

是的,所有的元素应该在容器内均匀分布,所以在第一个元素之前和最后一个之后填充。 – Joe

+0

因此,总高度减去div的高度,然后除以4. – epascarello

回答

0

其实,你只是在你的代码中缺少一个layer。虽然我只是猜测,因为我的代码中没有定义layer,但这是spaces,对吧?

spaces在我的代码中,指的是容器和孩子之间的空间。既然你说,必须有容器和第一个和最后的div之间的“填充”,计数将始终+ 1

function distribute() { 
 
    const container = document.getElementById('element_1'); 
 
    const containerHeight = container.getBoundingClientRect().height; 
 
    const children = container.querySelectorAll('div'); 
 
    const childHeight = children[0].getBoundingClientRect().height; 
 
    const spaces = children.length + 1; 
 
    const spaceInPx = (containerHeight - (childHeight * children.length))/spaces; 
 
    
 
    children.forEach((child, i) => { 
 
    const position = spaceInPx * (i + 1) + (childHeight * i); 
 
    
 
    child.style.top = `${position}px`; 
 
    }); 
 
} 
 

 
distribute();
#element_1 { 
 
    background: #000; 
 
} 
 

 
#element_1 div { 
 
    background: #666; 
 
}
<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>

相关问题