0

我正在使用以下代码(网页中的 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

我原以为这应该是相当简单的......但是它让我发疯......任何帮助表示赞赏。

4

2 回答 2

0

您需要将 _structure.style.position 设置为 'relative'、'absolute'、'fixed' 或 'sticky' 才能使用顶部、左侧、右侧、底部。

于 2019-11-11T00:24:14.790 回答
0

您需要将您的位置设置为真实或绝对才能使其工作,还要注意 position: absolute 根据最近的相对定位父级设置位置,而 position: relative 位置根据元素的当前位置

于 2019-11-11T00:28:28.547 回答