DIV CSS 佈局教程網

jQuery DOM 操作總整理:三大分類與實戰範例
編輯:JQuery特效代碼     

DOM 操作的三個層次

談到前端開發,DOM 幾乎是每天 must 面對的課題。很多人把 DOM 直接等同於 JavaScript,其實這是個常見的誤解。DOM 是一份獨立的規範,可以拆成三個彼此分工的子集合:DOM Core、HTML-DOM 與 CSS-DOM。理解這三者的界線,之後看 jQuery 的 API 會清楚很多。

1. DOM Core:與程式語言無關的核心標準

DOM Core 並不是 JavaScript 的專利。任何支援 DOM 的語言都能使用它,而且它的應用範圍也不侷限於網頁——只要是標記語言撰寫的文件,例如 XML,都適用。

我們熟悉的 getElementById()、getElementByTagName()、getAttribute() 與 setAttribute(),全都屬於 DOM Core 的範疇。

2. HTML-DOM:專為 HTML 加料的便捷介面

HTML-DOM 在 Core 之上補了一批更貼近 HTML 文件 habit 的屬性與方法,讓常見操作不必繞路。例如取得所有表單物件:

document.forms

直接取得某個元素的 src:

element.src

3. CSS-DOM:動態操控樣式

CSS-DOM 負責的正是樣式。在 JavaScript 裡,它的主要作用是讀取與設定 style 物件的各項屬性;只要改變這些屬性,頁面就能呈現完全不同的視覺效果。

element.style.color = "red";

jQuery 接手之後

jQuery 作為一個 JavaScript 函式庫,把上述 DOM 操作能力重新包裝得更短、更好用,讓開發者能把注意力放在「要做什麼」而不是「怎麼選到它」。以下用一個完整的範例,示範元素的建立、複製、重組與修飾。

CSS 部分

.chapter { width: 42em; }
a.link { text-decoration: none; }
span.footnote {
  font-style: italic;
  font-family: "Times New Roman", Times, serif;
  display: block;
  margin: 1em 0;
}
.text-reference { font-weight: bold; }
#notes { margin-top: 1em; border-top: 1px solid #00ff00; }
#notes li { margin: 1em 0; }
#footer { margin-top: 1em; border-top: 1px solid #dedede; }
.inhabitants { border-bottom: 1px solid #dedede; }
.pulled-wrapper {
  background: url(pq-top.jpg) no-repeat left top;
  position: absolute;
  width: 160px;
  right: -180px;
  padding-top: 18px;
}
.pulled {
  background: url(pq-bottom.jpg) no-repeat left bottom;
  position: relative;
  display: block;
  width: 140px;
  padding: 0 10px 24px 10px;
  font: italic 1.4em "Times New Roman", Times, serif;
}

為每個段落加上 class

$(document).ready(function() {
  $('p').each(function(index) {
    var currentClass = $(this).attr('class');
    $(this).attr('class', currentClass + ' inhabitants');
  });
});

動態為特定連結加上多個屬性

each() 的角色近似 for 迴圈,它會逐一走訪集合中的每個元素,第一個參數就是該元素的索引。

$(document).ready(function() {
  $('div.chapter a[href*=cnblogs]').each(function(index) {
    var $thisLink = $(this);
    $(this).attr({
      'rel': 'subsection',
      'id': 'blogslink-' + index,
      'title': '更多 ' + $thisLink.text() + ' 的說明',
      'class': 'link'
    });
  });
});

插入「回到頂端」連結

$(document).ready(function() {
  $('<a id="top" name="top">Top</a>').prependTo('body');
  $('div.chapter p:gt(0)').after('<a href="#top">回到頂端</a>');
  // 以下寫法與上面等效
  // $('<a href="#top">回到頂端</a>').insertAfter('div.chapter p:gt(0)');
});

:gt(n) 代表「從索引 n 之後開始」,因此這段程式會為第一個段落以外的每個段落都補上一顆回頂連結。

把註腳集中搬到列表裡

$(document).ready(function() {
  $('<ol id="notes"></ol>').insertAfter('div.chapter');
  $('span.footnote').each(function(index) {
    $(this)
      .before('<a href="#foot-note-' + (index + 1) + '" id="context-' + (index + 1) +
              '" class="context"><sup>' + (index + 1) + '</sup></a>')
      .appendTo('#notes')
      .append(' (<a href="#context-' + (index + 1) + '">本文</a>)')
      .wrap('<li id="foot-note-' + (index + 1) + '"></li>');
  });
});

這裡有幾個關鍵動作:before() 在元素前面插入錨點連結;appendTo() 把自己搬進 <ol>(注意這是「移動」而非複製);append() 往內容尾端補字;wrap() 則用指定的標籤把元素包起來。

拉出旁註:複製、改寫、定位

$(document).ready(function() {
  $('span.pull-quote').each(function(index) {
    var $parentParagraph = $(this).parent('p');
    $parentParagraph.css('position', 'relative');
    var $clonedCopy = $(this).clone();
    $clonedCopy
      .addClass('pulled')
      .find('span.drop')
      .html('…')
      .end()
      .prependTo($parentParagraph)
      .wrap('<div class="pulled-wrapper"></div>');
    var clonedText = $clonedCopy.text();
    $clonedCopy.html(clonedText);
  });
});

clone() 預設會連內容一起複製;end() 可以回到上一個未被改變的 jQuery 物件狀態,讓鏈式呼叫更好讀。

HTML 結構

<span class="footnote">註腳一</span>
<span class="footnote">註腳二</span>

<div class="chapter">
  <p>1. <a href="https://example.com">jQuery</a> 動態為連結加上屬性。</p>
  <p>2. <span class="pull-quote">第一段旁註<span class="drop">省略部分</span></span></p>
  <p>3. <span class="pull-quote">第二段旁註<span class="drop">省略部分</span></span></p>
</div>
<div id="footer">版權宣告</div>

把這幾段組合起來,你會得到一個具備段落樣式、註腳自動編號、回頂連結與旁註浮框的完整頁面——而這一切幾乎沒有手寫 HTML 的部分,全是 jQuery 在 DOM 上「長」出來的。

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