Dom編程藝術1-平穩退化

1.兼容getElementsByClassName

function getElementByClassName(node,classname){
    if(node.getElementsByClassName){
        //使用現有的方法
        return node.getElementsByClassName(classname);
    } else {
        var results=new Array();
        var elems = node.getElementsByTagName("*");
        for(var i=0;i<elems.length;i++){
            if(elems[i].className.indexOf(classname) != -1){
                results[results.length] = elems[i];
            }
        }
    }
}

2.獲取屬性getAttribute,getAttribute

var shopping=document.getElementById("purchases");
alert(shopping.getAttribute("title"));
shopping.setAttribute("title","a list of goods");
alert(shopping.getAttribute("title"));

3.value 和 src

//下面兩個等價
element.value="new value";
element.setAttribute("value","new value");

element.src="href";
element.setAttribute("src","new value");

4.childNodes

用下面語法獲取節點的nodeType屬性

node.nodeType
//nodeType屬性共有12種可取值,但其中僅有3種有價值
1.元素節點的nodeType 屬性值為1
2.屬性節點的nodeType 屬性值為2
3.文本節點的nodeType 屬性值為3
```
如果想獲得一個文本節點的值
```
node.nodeValue;
```
獲取第一個和最后一個節點
```
node.firstChild == node.childNodes[0]
node.lastChild == node.childNodes[node.childNodes.length-1]
```
具體應用,動態切換圖片
```
function showPic(whichpic) {
  var source = whichpic.getAttribute("href");
  var placeholder = document.getElementById("placeholder");
  placeholder.setAttribute("src",source);
  var text = whichpic.getAttribute("title");
  var description = document.getElementById("description");
  description.firstChild.nodeValue = text;
}
<a href="images/fireworks.jpg" title="A fireworks display" 
      onclick="showPic(this); return false;">
Fireworks
</a>
 <img id="placeholder" src="images/placeholder.gif" alt="my image gallery" />
```

####5.一個平穩退化的例子
```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Example</title>
<script type="text/JavaScript">
window.onload = function() {
  if (!document.getElementsByTagName) return false;
  var lnks = document.getElementsByTagName("a");
  for (var i=0; i<lnks.length; i++) {
    if (lnks[i].getAttribute("class") == "popup") {
      lnks[i].onclick = function() {
        popUp(this.getAttribute("href"));
        return false;
      }
    }
  }
}

function popUp(winURL) {
  window.open(winURL,"popup","width=320,height=480");
}

</script>
</head>
<body>
//樣式分離,并沒有增加什么js代碼
//<a  onclick="popUp(this.href);return false;">Example</a>
<a  class="popup">Example</a>
</body>
</html>

```

####6.圖片庫代碼改進
```
//點擊事件處理函數
function showPic(whichpic) {
  if (!document.getElementById("placeholder")) return true;
  var source = whichpic.getAttribute("href");
  var placeholder = document.getElementById("placeholder");
  placeholder.setAttribute("src",source);
  if (!document.getElementById("description")) return false;
  //判斷title屬性是否存在
  if (whichpic.getAttribute("title")) {
    var text = whichpic.getAttribute("title");
  } else {
    var text = "";
  }
  var description = document.getElementById("description");
  if (description.firstChild.nodeType == 3) {
    description.firstChild.nodeValue = text;
  }
  return false;//不讓瀏覽器執行默認行為
}

//為連接增加點擊事件,一個函數只有一個出口并集中在開頭位置
function prepareGallery() {
  if (!document.getElementsByTagName) return false;
  if (!document.getElementById) return false;
  //預防性措施
  if (!document.getElementById("imagegallery")) return false;
  var gallery = document.getElementById("imagegallery");
  var links = gallery.getElementsByTagName("a");
  for ( var i=0; i < links.length; i++) {
    links[i].onclick = function() {
      return showPic(this);
      }
    //最好不使用,因為onclick也支持按鍵
   // links[i].onkeypress = links[i].onclick;
  }
}
//共享onload事件
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

addLoadEvent(prepareGallery);
```
```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Image Gallery</title>
    <script type="text/javascript" src="scripts/showPic.js"></script>
    <link rel="stylesheet" href="styles/layout.css" type="text/css" media="screen" />
</head>
<body>
  <h1>Snapshots</h1>
  <ul id="imagegallery">
    <li>
      <a href="images/fireworks.jpg" title="A fireworks display">
        <img src="images/thumbnail_fireworks.jpg" alt="Fireworks" />
      </a>
    </li>
    <li>
      <a href="images/coffee.jpg" title="A cup of black coffee" >
        <img src="images/thumbnail_coffee.jpg" alt="Coffee" />
      </a>
    </li>
    <li>
      <a href="images/rose.jpg" title="A red, red rose">
        <img src="images/thumbnail_rose.jpg" alt="Rose" />
      </a>
    </li>
    <li>
      <a href="images/bigben.jpg" title="The famous clock">
        <img src="images/thumbnail_bigben.jpg" alt="Big Ben" />
      </a>
    </li>
  </ul>
  <img id="placeholder" src="images/placeholder.gif" alt="my image gallery" />
  <p id="description">Choose an image.</p>
</body>
</html>

```

####7.動態創建標記
傳統方法,沒有做到樣式和行為分離,不推薦
```
 <script type="text/javascript">
    document.write("<p>This is inserted.</p>");
  </script>
```
把一大段html放入文檔中innerHTML
```
var testdiv = document.getElementById("testdiv");
  testdiv.innerHTML="<p>I inserted <em>this</em> content.</p>";
```
#####dom方法
用到的這幾個方法或者屬性
parentNode 屬性
lastChild 屬性
appendChild 方法
insertBefore 方法
nextSibling 屬性
```
window.onload = function() {
  var para = document.createElement("p");
  var txt1 = document.createTextNode("I inserted ");
  var emphasis = document.createElement("em");
  var txt2 = document.createTextNode("this");
  var txt3 = document.createTextNode(" content.");
  para.appendChild(txt1);
  emphasis.appendChild(txt2);
  para.appendChild(emphasis);
  para.appendChild(txt3);
  var testdiv = document.getElementById("testdiv");
  testdiv.appendChild(para);
}
```
圖片庫代碼,剛開始展示的文字和圖片用js生成
#####注意插入之前gallery.parentNode.insertBefore(placeholder,gallery);
#####沒有insertAfter
```
function preparePlaceholder() {
  if (!document.createElement) return false;
  if (!document.createTextNode) return false;
  var placeholder = document.createElement("img");
  placeholder.setAttribute("id","placeholder");
  placeholder.setAttribute("src","images/placeholder.gif");
  placeholder.setAttribute("alt","my image gallery");
  var description = document.createElement("p");
  description.setAttribute("id","description");
  var desctext = document.createTextNode("Choose an image");
  description.appendChild(desctext);
  var gallery = document.getElementById("imagegallery");
  gallery.parentNode.insertBefore(placeholder,gallery);
  gallery.parentNode.insertBefore(description,gallery);
}
```
自己實現一個insertAfter
 ```
function insertAfter(newElement,targetElement) {
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement,targetElement.nextSibling);
  }
}
```
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 原文 鏈接 關注公眾號獲取更多資訊 一、基本類型介紹 1.1 Node類型 DOM1級定義了一個Node接口,該接...
    前端進階之旅閱讀 3,967評論 7 34
  • 復習 document對象提供了哪五種訪問DOM元素的方法? history、location對象分別有哪些常用方...
    輕思維閱讀 671評論 0 3
  • 前言 歸根結底,代碼都是思想和概念的體現。沒人能把一種程序設計語言的所有語法和關鍵字都記住,可以查閱參考書來解決。...
    朱細細閱讀 2,979評論 4 14
  • 最近懷舊比較多,想起深圳,想起進的玩具廠,路邊買一個批量處理的收錄機,全場30,有個白色的,特別好看,立體聲的,如...
    瞿桂林閱讀 36評論 0 0
  • 有人和我說照顧植物可以培養自己的心性。會更加平和一點,耐心一點,細心一點。 這句話不是沒有道理。 養了植物以後會比...
    蘇步閱讀 159評論 0 2