1. 程式人生 > 實用技巧 >3.案例研究:JavaScript圖片庫

3.案例研究:JavaScript圖片庫

可以自行進行測試,images可以自己在網上找。下編將介紹最佳實踐並修正我們下面的程式碼!

1. 編寫一個優秀的標記檔案

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Image Gallery</title>
</head>
<body>
  <h1>Snapshots</h1>
  <ul>
    <li>
      <a href="
images/fireworks.jpg" title="A fireworks display" onclick="showPic(this); return false;">Fireworks</a> // return false是為了阻止連結的預設行為 </li> <li> <a href="images/coffee.jpg" title="A cup of black coffee" onclick="showPic(this); return false;">Coffee</a> </li> <li> <a href="
images/rose.jpg" title="A red, red rose" onclick="showPic(this); return false;">Rose</a> </li> <li> <a href="images/bigben.jpg" title="The famous clock" onclick="showPic(this); return false;">Big Ben</a> </li> </ul> <img src="images/placeholder.gif
" alt="my image gallery" id="placeholder"> <script src="scripts/showPic.js"> </script> </body> </html>

2.編寫一個JS函式以顯示使用者想要檢視的圖片及其文字

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;
}

3.CSS程式碼:

body {
  font-family: "Helvetica","Arial",serif;
  color: #333;
  background-color: #ccc;
  margin: 1em 10%;
}
h1 {
  color: #333;
  background-color: transparent;
}
a {
  color: #c60;
  background-color: transparent;
  font-weight: bold;
  text-decoration: none;
}
ul {
  padding: 0;
}
li {
  float: left;
  padding: 1em;
  list-style: none;
}
img {
  display:block;
  clear: both;
}