DIV CSS 佈局教程網

JavaScript 動態建立與移除 div 元素
編輯:JavaScript綜合知識     

動態建立元素

JavaScript 可用 document.createElement() 建立元素,再透過 appendChild() 加入頁面。若要移除元素,可使用 removeChild()。

範例程式

function createDiv(title) {
  const old = document.getElementById('newD');

  if (old) {
    document.body.removeChild(old);
  }

  const div = document.createElement('div');
  div.id = 'newD';
  div.style.position = 'absolute';
  div.style.height = '160px';
  div.style.width = '400px';
  div.style.border = '1px solid grey';
  div.style.background = 'white';
  div.style.paddingTop = '40px';
  div.style.zIndex = '100';
  div.style.left = '100px';
  div.style.top = '100px';
  div.style.textAlign = 'center';
  div.style.fontSize = '18px';
  div.textContent = title;

  document.body.appendChild(div);
}

function removeDiv() {
  const div = document.getElementById('newD');

  if (div) {
    document.body.removeChild(div);
  }
}

重點說明

在 Firefox 等瀏覽器中,設定 left、top、width、height 等樣式時,記得加上單位,例如 px。動態建立元素後,也可再綁定事件或加入其他子元素。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved