使用 DOM 進行 Web 和 XML 開發的示例

本章提供了一些使用 DOM 進行 Web 和 XML 開發的較長示例。在可能的情況下,這些示例使用 JavaScript 中用於操作文件物件的常用 API、技巧和模式。

示例 1:高度和寬度

以下示例顯示瞭如何將heightwidth屬性與不同尺寸的影像一起使用

html
<!doctype html>
<html lang="en">
  <head>
    <title>width/height example</title>
    <script>
      function init() {
        const arrImages = new Array(3);

        arrImages[0] = document.getElementById("image1");
        arrImages[1] = document.getElementById("image2");
        arrImages[2] = document.getElementById("image3");

        const objOutput = document.getElementById("output");
        let strHtml = "<ul>";

        for (let i = 0; i < arrImages.length; i++) {
          strHtml +=
            "<li>image" +
            (i + 1) +
            ": height=" +
            arrImages[i].height +
            ", width=" +
            arrImages[i].width +
            ", style.height=" +
            arrImages[i].style.height +
            ", style.width=" +
            arrImages[i].style.width +
            "</li>";
        }

        strHtml += "</ul>";

        objOutput.innerHTML = strHtml;
      }
    </script>
  </head>
  <body onload="init();">
    <p>
      Image 1: no height, width, or style
      <img
        id="image1"
        src="https://www.mozilla.org/images/mozilla-banner.gif" />
    </p>

    <p>
      Image 2: height="50", width="500", but no style
      <img
        id="image2"
        src="https://www.mozilla.org/images/mozilla-banner.gif"
        height="50"
        width="500" />
    </p>

    <p>
      Image 3: no height, width, but style="height: 50px; width: 500px;"
      <img
        id="image3"
        src="https://www.mozilla.org/images/mozilla-banner.gif"
        style="height: 50px; width: 500px;" />
    </p>

    <div id="output"></div>
  </body>
</html>

示例 2:影像屬性

html
<!doctype html>
<html lang="en">
  <head>
    <title>Modifying an image border</title>

    <script>
      function setBorderWidth(width) {
        document.getElementById("img1").style.borderWidth = width + "px";
      }
    </script>
  </head>

  <body>
    <p>
      <img
        id="img1"
        src="image1.gif"
        style="border: 5px solid green;"
        width="100"
        height="100"
        alt="border test" />
    </p>

    <form name="FormName">
      <input
        type="button"
        value="Make border 20px-wide"
        onclick="setBorderWidth(20);" />
      <input
        type="button"
        value="Make border 5px-wide"
        onclick="setBorderWidth(5);" />
    </form>
  </body>
</html>

示例 3:操作樣式

在這個簡單的示例中,HTML 段落元素的一些基本樣式屬性是使用元素上的style物件以及該物件的 CSS 樣式屬性訪問的,這些屬性可以從 DOM 中檢索和設定。在這種情況下,您正在直接操作各個樣式。在下一個示例(參見示例 4)中,您可以使用樣式表及其規則更改整個文件的樣式。

html
<!doctype html>
<html lang="en">
  <head>
    <title>Changing color and font-size example</title>

    <script>
      function changeText() {
        const p = document.getElementById("pid");

        p.style.color = "blue";
        p.style.fontSize = "18pt";
      }
    </script>
  </head>
  <body>
    <p id="pid" onclick="window.location.href = 'http://www.cnn.com/';">
      linker
    </p>

    <form>
      <p><input value="rec" type="button" onclick="changeText();" /></p>
    </form>
  </body>
</html>

示例 4:使用樣式表

document物件上的styleSheets屬性返回已載入到該文件上的樣式表的列表。您可以使用樣式表、樣式和CSSRule物件單獨訪問這些樣式表及其規則,如本示例所示,該示例將所有樣式規則選擇器列印到控制檯。

js
const ss = document.styleSheets;

for (let i = 0; i < ss.length; i++) {
  for (let j = 0; j < ss[i].cssRules.length; j++) {
    console.log(`${ss[i].cssRules[j].selectorText}\n`);
  }
}

對於具有單個樣式表的文件,其中定義了以下三個規則

css
body {
  background-color: darkblue;
}
p {
  font-family: Arial;
  font-size: 10pt;
  margin-left: 0.125in;
}
#lumpy {
  display: none;
}

此指令碼輸出以下內容

BODY
P
#LUMPY

示例 5:事件傳播

此示例以非常簡單的方式演示了事件如何在 DOM 中觸發和處理。當此 HTML 文件的 BODY 載入時,事件偵聽器會註冊到 TABLE 的頂行。事件偵聽器透過執行函式stopEvent來處理事件,該函式更改表底部單元格中的值。

但是,stopEvent還會呼叫事件物件方法event.stopPropagation,這可以防止事件進一步冒泡到 DOM 中。請注意,表本身有一個onclick事件處理程式,該處理程式應該在單擊表時顯示訊息。但是,stopEvent方法已停止傳播,因此在更新表中的資料後,事件階段實際上已結束,並且會顯示一個警報框以確認這一點。

html
<!doctype html>
<html lang="en">
  <head>
    <title>Event Propagation</title>

    <style>
      #t-daddy {
        border: 1px solid red;
      }
      #c1 {
        background-color: pink;
      }
    </style>

    <script>
      function stopEvent(event) {
        const c2 = document.getElementById("c2");
        c2.textContent = "hello";

        // this ought to keep t-daddy from getting the click.
        event.stopPropagation();
        alert("event propagation halted.");
      }

      function load() {
        const elem = document.getElementById("tbl1");
        elem.addEventListener("click", stopEvent, false);
      }
    </script>
  </head>

  <body onload="load();">
    <table id="t-daddy" onclick="alert('hi');">
      <tr id="tbl1">
        <td id="c1">one</td>
      </tr>
      <tr>
        <td id="c2">two</td>
      </tr>
    </table>
  </body>
</html>

示例 6:getComputedStyle

此示例演示瞭如何使用window.getComputedStyle方法獲取未使用style屬性或 JavaScript(例如,elt.style.backgroundColor="rgb(173 216 230)")設定的元素的樣式。可以使用更直接的elt.style屬性檢索後一種型別的樣式,其屬性列在DOM CSS 屬性列表中。

getComputedStyle()返回一個CSSStyleDeclaration物件,可以使用此物件的getPropertyValue()方法引用其各個樣式屬性,如下面的示例文件所示。

html
<!doctype html>
<html lang="en">
  <head>
    <title>getComputedStyle example</title>

    <script>
      function cStyles() {
        const RefDiv = document.getElementById("d1");
        const txtHeight = document.getElementById("t1");
        const h_style = document.defaultView
          .getComputedStyle(RefDiv, null)
          .getPropertyValue("height");

        txtHeight.value = h_style;

        const txtWidth = document.getElementById("t2");
        const w_style = document.defaultView
          .getComputedStyle(RefDiv, null)
          .getPropertyValue("width");

        txtWidth.value = w_style;

        const txtBackgroundColor = document.getElementById("t3");
        const b_style = document.defaultView
          .getComputedStyle(RefDiv, null)
          .getPropertyValue("background-color");

        txtBackgroundColor.value = b_style;
      }
    </script>

    <style>
      #d1 {
        margin-left: 10px;
        background-color: rgb(173 216 230);
        height: 20px;
        max-width: 20px;
      }
    </style>
  </head>

  <body>
    <div id="d1">&nbsp;</div>

    <form action="">
      <p>
        <button type="button" onclick="cStyles();">getComputedStyle</button>
        height<input id="t1" type="text" value="1" /> max-width<input
          id="t2"
          type="text"
          value="2" />
        bg-color<input id="t3" type="text" value="3" />
      </p>
    </form>
  </body>
</html>

示例 7:顯示事件物件屬性

此示例使用 DOM 方法在表格中顯示onloadevent物件的所有屬性及其值。它還顯示了一種使用for...in迴圈迭代物件屬性以獲取其值的實用技術。

事件物件的屬性在不同瀏覽器之間差異很大,WHATWG DOM 標準列出了標準屬性,但許多瀏覽器都對其進行了大量擴充套件。

將以下程式碼放入一個空白文字檔案中,並將其載入到各種瀏覽器中,您會對屬性的數量和名稱的不同感到驚訝。您可能還想在頁面中新增一些元素,並從不同的事件處理程式呼叫此函式。

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Show Event properties</title>

    <style>
      table {
        border-collapse: collapse;
      }
      thead {
        font-weight: bold;
      }
      td {
        padding: 2px 10px 2px 10px;
      }

      .odd {
        background-color: #efdfef;
      }
      .even {
        background-color: #ffffff;
      }
    </style>

    <script>
      function showEventProperties(e) {
        function addCell(row, text) {
          const cell = row.insertCell(-1);
          cell.appendChild(document.createTextNode(text));
        }

        const event = e || window.event;
        document.getElementById("eventType").textContent = event.type;

        const table = document.createElement("table");
        const thead = table.createTHead();
        let row = thead.insertRow(-1);
        const labelList = ["#", "Property", "Value"];
        const len = labelList.length;

        for (let i = 0; i < len; i++) {
          addCell(row, labelList[i]);
        }

        const tbody = document.createElement("tbody");
        table.appendChild(tbody);

        for (const p in event) {
          row = tbody.insertRow(-1);
          row.className = row.rowIndex % 2 ? "odd" : "even";
          addCell(row, row.rowIndex);
          addCell(row, p);
          addCell(row, event[p]);
        }

        document.body.appendChild(table);
      }

      window.onload = (event) => {
        showEventProperties(event);
      };
    </script>
  </head>

  <body>
    <h1>Properties of the DOM <span id="eventType"></span> Event Object</h1>
  </body>
</html>

示例 8:使用 DOM 表格介面

DOM HTMLTableElement介面提供了一些用於建立和操作表格的便捷方法。兩種常用的方法是HTMLTableElement.insertRowHTMLTableRowElement.insertCell

要向現有表格新增行和一些單元格

html
<table id="table0">
  <tr>
    <td>Row 0 Cell 0</td>
    <td>Row 0 Cell 1</td>
  </tr>
</table>

<script>
  const table = document.getElementById("table0");
  const row = table.insertRow(-1);
  let cell;
  let text;

  for (let i = 0; i < 2; i++) {
    cell = row.insertCell(-1);
    text = "Row " + row.rowIndex + " Cell " + i;
    cell.appendChild(document.createTextNode(text));
  }
</script>

注意

  • 永遠不要使用表格的innerHTML屬性修改表格,儘管您可以使用它來編寫整個表格或單元格的內容。
  • 如果使用 DOM Core 方法document.createElementNode.appendChild建立行和單元格,則 IE 要求將它們附加到<tbody>元素,而其他瀏覽器則允許附加到<table>元素(行將新增到最後一個<tbody>元素)。
  • HTMLTableElement介面還有許多其他便捷方法可用於建立和修改表格。