簡體   English   中英

使用setAttribute后如何使position成為絕對值而不是“未定義”

[英]How to get position to be absolute rather than 'undefined' after using setAttribute

我正在嘗試將名為“spell”的數組的屬性分配給位於 div 容器中的新創建的 img 元素。

for (let i = 0; i <spell.length; i++){
          let styles = spell[i]
          let container = document.getElementById('imagecontainer');
          let newImg = document.createElement('img');

          let top = styles.top;
          let left = styles.left;
          let imgSrc = styles.src;
          newImg.setAttribute('width','25px');
          newImg.setAttribute('left',left);
          newImg.setAttribute('top',top);
          newImg.setAttribute('src',imgSrc);
          newImg.setAttribute('height','25px')
          newImg.setAttribute('position','absolute');
            console.log(newImg.position)
          container.appendChild(newImg);
        }

但是,當我運行代碼時,它會將所有圖像的 newImg.position 記錄為未定義。 我不確定哪里出了問題

設置style屬性的屬性: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

 const spell = [{ top: "10px", left: "10px", src: "foo.png" }, { top: "50px", left: "50px", src: "bar.png" }]; const container = document.getElementById('imagecontainer'); for (let i = 0; i < spell.length; i++) { let styles = spell[i]; let newImg = document.createElement('img'); let top = styles.top; let left = styles.left; let imgSrc = styles.src; newImg.style.width = '25px'; newImg.style.height = '25px'; newImg.style.top = top; newImg.style.left = left; newImg.style.position = 'absolute'; newImg.setAttribute("src", imgSrc); console.log(newImg.style.position); container.appendChild(newImg); }
 <div id="imagecontainer"></div>

暫無
暫無

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

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