【问题标题】:positioning new element based on position of existing element?根据现有元素的位置定位新元素?
【发布时间】:2019-11-11 08:28:28
【问题描述】:

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

    您需要将 _structure.style.position 设置为 'relative'、'absolute'、'fixed' 或 'sticky' 才能使用 top、left、right、bottom。

    【讨论】:

    • 非常感谢,我想这回答了我在上一篇文章中的评论问题。问候。
    【解决方案2】:

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

    【讨论】:

    • 谢谢...今晚晚些时候我会试一试。似乎有道理。我想语法是“_structure.style.position = absolute;” (或亲戚)...对吗?再次感谢您,非常感谢。
    • 正确,只是你可能需要在引号中设置绝对值
    • 再次感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2014-05-21
    • 2022-09-28
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2013-06-16
    相关资源
    最近更新 更多