Javascript DOM编程艺术读书笔记4

第4章 案例研究:JS图片库

  • DOM是一种适用于多种环境和多种程序设计语言的通用型API。
  • node.firstChild与node.childNodes[0]完全等价
  • 如果想要得到<p id="description">haha</p>其中文本节点的值。若用description.nodeValue则值为NULL,因为<p>元素本身的nodeValue属性是一个空值,需要用description.firstChild.nodeValue.
  • 元素节点nodeType属性值是1
  • 属性节点nodeType属性值是2
  • 文本节点nodeType属性值是3

文件结构

1
2
3
4
5
6
7
8
9
10
11
12
│  gallery.html

├─images
│ 1.jpg
│ 2.jpg
│ 3.jpg

├─scripts
│ show.js

└─styles
layout.css

gallery.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>Image Gallery</title>
<link rel="stylesheet" type="text/css" href="styles/layout.css">
</head>

<body>
<h1>Snapshots</h1>
<ul>
<li>
<a href="./images/1.jpg" title="A fireworks display" onclick="showPic(this); return false;">Fireworks</a></li>
<li>
<a href="images/2.jpg" title="A cup of black coffee" onclick="showPic(this); return false;">Coffee</a>
</li>
<li>
<a href="images/3.jpg" title="A red, red rose" onclick="showPic(this); return false;">Rose</a>
</li>
</ul>
<img id="placeholder" src="images/placeholder.gif"/>
<p id="description">Choose an image</p>
<script src="scripts/show.js">
</script>
</body>

</html>

showPic.js

1
2
3
4
5
6
7
8
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;
}

layout.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
}