<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml: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>
showPic.js檔案內容:
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; if (whichpic.getAttribute("title")) { var text = whichpic.getAttribute("title"); // 得到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"); // 先找到某一個id的元素 var links = gallery.getElementsByTagName("a"); // 在此id下找到所有a的元素 for ( var i=0; i < links.length; i++) { // 對每個a進行分析(掛上onclick事件),這樣做的好處是不用動html裡一行程式碼 links[i].onclick = function() { return showPic(this); } links[i].onkeypress = links[i].onclick; // 讓 onkeypress 等於 onclick 事件 } } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } addLoadEvent(prepareGallery); // 自動在檔案載入的時候就執行。