案例研究:javascript图片库
re0.htm
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>RE:从零开始</title>
<link rel="stylesheet" href="layout.css" media="screen" />
</head>
<body>
<h1>RE:从零开始的异世界生活</h1>
<ul>
<li>
<a href="https://img-blog.youkuaiyun.com/20170226215411985" title="从零开始" onclick="showPic(this);describe(this);return false;">re:从零开始</a>
</li>
<li>
<a href="https://img-blog.youkuaiyun.com/20170226215433813" title="蕾姆" onclick="showPic(this);describe(this);return false;">re:蕾姆</a>
</li>
<li>
<a href="https://img-blog.youkuaiyun.com/20170226215427329" title="艾米莉亚" onclick="showPic(this);describe(this);return false;">re:艾米莉亚</a>
</li>
</ul>
<img id="placeholder" src="https://img-blog.youkuaiyun.com/20170226215704455" width="500" height="300" title="mypic" />
<p id="description">这是要展示的图片名称</p>
<script type="text/javascript">
function showPic(whichpic){
var pic = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src", pic);
}
function describe(pic){
var text = pic.getAttribute("title");
var description = document.getElementById("description").childNodes[0];
description.nodeValue = text;
}
</script>
</body>
</html>
layout.css
body {
font-family: "Helvetica","Arial",serif;
color: #333;
background-color: #ccc;
margin: 1em 10%;
}
h1 {
color: #333;
background-color: transparent;
}
a,p {
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;
}
把上面的文件保存在同一文件夹下,就ok啦!
知识点梳理
DOM的几个新属性:
childNodes
eg:获取body下所有子节点
//获取body下所有childNodes的个数
function countBodyChildren(){
var body_element = document.getElementsByTagName("body")[0];
var sum = body_element.childNodes.length;
alert(sum);
}
firstChild
lastChild
顾名思义,返回某元素的第一个子节点和最后一个子节点
node.firstChild 和 node.chidNodes[0] 是等价的
node.lastChild 和 node.childNodes[node.childNodes.length-1]是等价的
nodeType
节点类型,总共有12种可取值,其中1-3种最常用,分别为:
元素节点:nodeType 为 1
属性节点:nodeType 为 2
文本节点:nodeType 为 3
nodeValue
获取文本节点的值
<p id="demo">这是文本节点的初始内容</p>
<button onclick="change()">点我改变内容</button>
<script>
function change() {
var pNode = document.getElementById("demo");
var textNode = pNode.firstChild;
textNode.nodeValue = "改变后的节点内容";
}
</script>