簡體   English   中英

基於現有元素的 position 定位新元素?

[英]positioning new element based on position of existing element?

我正在使用以下代碼(網頁中的 Javascript)在 DOM 中動態創建一個“新”元素。 我希望 position 這說 200px“低於”現有元素。 但是,我的 output 的新元素的定位都錯了……好像我指定的 position(頂部,左側)被忽略了。

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

我原以為這應該是相當簡單的......但是它讓我發瘋......任何幫助表示贊賞。

您需要將 _structure.style.position 設置為“相對”、“絕對”、“固定”或“粘性”,以便使用頂部、左側、右側、底部。

You need to set your position to realtive or absolute in order for this to work, also note that position: absolute sets the position according to the nearest relative positioned parent while position: relative positions according to the current position of the element

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM