根据现有元素的位置来放置新元素?

问题描述 投票:0回答:1

我正在使用以下代码(网页中的Javascript)在DOM中动态创建“新”元素。我希望将这个200px定位在现有元素“下方”。但是我的输出中所有新元素的位置都错误了...好像我指定的位置(顶部,左侧)被忽略了。

var _reference = document.getElementById("outputs");

for (_count = 0; _count < _limits; _count++) {

 var _structure = document.createElement("div"); 
 _structure.setAttribute("class", "container-fluid");
 _structure.setAttribute("id", "struct_" + _tally);
  if (_count === 0){
  _rect = _reference.getBoundingClientRect();  
    //get the bounding box of the "outputs" id element...
  document.getElementById("outputs").appendChild(_structure);   
  _structure.style.top = _rect.top + "200px";  //NOT positioned 200px below 'outputs'
  _structure.style.left = _rect.left;  //NOT positioned same position as 'outputs'
  }  //_count is "0"

}  //for loop

我本以为这应该很简单...但是它使我发疯...任何帮助表示赞赏。

javascript positioning appendchild getboundingclientrect
1个回答
0
投票

为了使用上,左,右,下,您需要将_structure.style.display设置为'relative','absolute'或'sticky'。

© www.soinside.com 2019 - 2024. All rights reserved.