前兩章講了如何取得 DOM 元素,本章開始說明如何操作 DOM。針對頁面上已有的 DOM 元素操作,無非就是對該元素的樣式進行操作;此外,我們也能用 JS 動態地向 HTML 寫入 DOM 元素。本章就談這兩種應用。
(一)操作 HTML 中現有的 DOM 元素
對現有元素操作,本質上就是操作樣式,因此首先要能取得元素的樣式。先說明樣式的三種連結方式:
一是直接寫在 HTML 標籤中,例如 <div style="width:300px;height:200px;background:#000;"></div>。
二是在 head 中用 style 標籤插入,例如 <style> #dom{width:300px;height:200px;background:#000;} </style>。
三是常用的外部連結方式,例如 <link rel="stylesheet" type="text/css" href="css.css" />。
這三種方式用 JS 操作的方法略有不同。重點說明第一種,因為它最常用也最方便。
第一種的操作方法,例如 <div id="dom" style="width:300px;height:200px;background:#000;margin-top:10px;"></div>,先取得元素:var a = document.getElementById("dom");,再取得屬性:var h = a.style.height;,寬度與背景類似:var w = a.style.width; var bg = a.style.background;。注意 margin-top 需用駝峰寫法:var mt = a.style.marginTop;。修改也很簡單,例如把高度改為 100:a.style.height = "100px";。
第二種(style 標籤)需要區分瀏覽器,因為 IE 與 FF 取得方式不同:var domcss = document.styleSheets[0].cssRules||document.styleSheets[0].rules; var a = domcss[0].style.height;,修改為 domcss[0].style.height = "100px";。
第三種(外部連結)也需區分瀏覽器,通常寫成函式:function CurrentStyle(element){ return element.currentStyle || document.defaultView.getComputedStyle(element, null); },取得方式如 var a = CurrentStyle("dom").height;,但無法用此法直接修改,只能用第一種方式修改。
(二)用 JS 動態建立 DOM 元素
這其實很簡單,只是幾個 JS 方法,但要像蓋房子一樣一步步來。以建立 <div id="dom" style="width:100px;height:100px;background:#000;margin-top:10px;"></div> 為例:
第一步,建立 div 節點:var newobj = document.createElement("div");
第二步,設定 id 屬性:newobj.setAttribute("id","dom");
第三步,設定樣式,有兩種方式:newobj.style.width = "100px"; 或 newobj.setAttribute("width","100px");,其餘屬性同理。
第四步,把節點放進文件:document.body.appendChild(newobj),其中 document.body 取得 body 元素,appendChild 向該元素加入子節點。若要移除則用 document.body.removeChild(newobj);。若想加到 id 為 con 的元素,則寫成 document.getElementById("con").appendChild(newobj)。
JS 中還有許多與 appendChild 類似的方法,用法相近,這裡不再贅述。本章就到這裡,下章開始教大家寫一些實際效果。