Javascript 根据现有元素的位置定位新元素?

Javascript 根据现有元素的位置定位新元素?,javascript,positioning,appendchild,getboundingclientrect,Javascript,Positioning,Appendchild,Getboundingclientrect,我正在使用以下代码(网页中的Javascript)在DOM中动态创建一个“新”元素。我想把这个200px放在一个现有元素下面。但是,我的输出中新元素的位置完全错误…好像我指定的位置(顶部,左侧)被忽略 var _reference = document.getElementById("outputs"); for (_count = 0; _count < _limits; _count++) { var _structure = document.createElement("di

我正在使用以下代码(网页中的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
var\u reference=document.getElementById(“输出”);
对于(_count=0;_count<_limits;_count++){
var_structure=document.createElement(“div”);
_setAttribute(“类”、“容器流体”);
_setAttribute(“id”,“struct”+_taly);
如果(_count==0){
_rect=_reference.getBoundingClientRect();
//获取“outputs”id元素的边界框。。。
document.getElementById(“输出”).appendChild(_结构);
_structure.style.top=_rect.top+“200px”;//未将200px定位在“输出”下方
_structure.style.left=_rect.left;//与“outputs”位置不同
}//\u计数为“0”
}//for循环

我本以为这应该是相当简单的…但是这让我发疯了…感谢您的任何帮助。

您需要将_structure.style.position设置为“相对”、“绝对”、“固定”或“粘滞”,以便使用top、left、right和bottom。

您需要将您的position设置为reactive或absolute以使其正常工作,还要注意的是,position:absolute根据最近的相对位置父元素设置位置,而position:relative positions根据元素的当前位置设置位置

谢谢……今晚晚些时候我会尝试一下。似乎有道理。我想语法应该是“_structure.style.position=absolute;”(或relative)…对吗?再次感谢您,非常感谢。正确,只有您可能需要在引号中设置绝对值再次感谢您的帮助:)非常感谢,我想这回答了我在上一篇文章中的评论问题。当做