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。動態建立元素後,也可再綁定事件或加入其他子元素。