利用DOM的方式點擊切換圖片及修改文字

本案例主要學習理解,用到的幾個DOM方法

01、getAttribute()方法,獲取元素的屬性值

02、setAttribute('src',source) 方法,用後邊的值修改前邊這個元素的屬性值

html基本框架代碼

1 <h1>圖片點擊切換</h1>
2     <ul id="imagegallery">
3         <li><a href="images/654.jpg" title="圖片一說明">圖片一</a></li>
4         <li><a href="images/contentimg.jpg" title="圖片二說明">圖片二</a></li>
5         <li><a href="images/tuku.jpg" title="圖片三說明">圖片三</a></li>
6     </ul>
7     <img src="images/toutiao3.jpg" alt="佔位圖" id="img">
8     <p id="description">圖片說明</p>

js相關代碼

實現的思路分解:

  01、用getAttribute()方法獲取到a標籤的href的屬性值

  02、用document.getElementById()方法獲取到圖片

  03、用setAttribute('要修改的元素屬性',用href的值修改)

點擊修改圖片基本思路就是這樣。

修改文字的思路,這裏爲了練習dom的相關方法,沒有使用innerHTML方法

  01、用getAttribute()方法獲取到a標籤的title的屬性值

  02、獲取要修改的id

  03、獲取p元素的第一個文本節點的值 用到firstChild.nodeValu獲取

  04、我們把獲取到的title的屬性值賦值給03步驟的變量

 1  function showpic(winpic){
 2             if(!document.getElementById('img')) return false;
 3             var source = winpic.getAttribute('href');
 4             var oImg = document.getElementById('img');
 5             if(oImg.nodeName !='IMG') return false;
 6             oImg.setAttribute('src',source);
 7             if(document.getElementById('description')){
 8                 var description = document.getElementById('description');
 9                 var text = winpic.getAttribute('title');
10                 description.firstChild.nodeValue = text;
11                 //description.innerHTML = text;
12             }
13             return true;
14         }
15 
16         function prepareGallery(){
17             if(!document.getElementsByTagName) return false;
18             if(!document.getElementById) return false;
19             if(!document.getElementById('imagegallery')) return false;
20             var gallery = document.getElementById('imagegallery');
21             var links = gallery.getElementsByTagName('a');
22             for(var i=0;i<links.length;i++){
23                 links[i].onclick = function(){
24                    //return showpic(this) ? return : false;
25                    showpic(this);
26                    return false;  
27                 }
28             }
29         }
30 
31         prepareGallery();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章