您的位置:首页 > Web前端 > JavaScript

js图片库(js dom 编程艺术第四章)

2016-09-11 16:28 351 查看
4.1标记

4.2javascript

4.3应用这个javascript函数:onclick

标记文档如下:

<body>
<h1>Snapshots</h1>
<ul>
<li>
<a href="images/fireworks.jpg" title="A fireworks display" onclick="showPic(this); return false;">Fireworks</a>
</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 id="placeholder" src="images/placeholder.gif" alt="my image gallery" />
</body>

.js函数代码

<script>
function showPic(whichpic) {
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src",source);//等同于 placeholder.setAttribute=source
}
</script>

4.4对这个函数进行扩展
4.4.1childNodes属性

在一棵节点树上childNodes属性可以用来获取任何一个元素的所有子元素。

语法:element.childNodes

function countbodychildren(){
var body_children=document.getElementsByTagName("body")[0];//[0]不可以漏
alert(body_children.childNodes.length);
}
window.onload=countbodychildren;

4.4.2nodeType属性
元素节点的nodeType属性值是1;

属性节点的nodeType属性值是2;

文本节点的nodeType属性值是3;



alert(body_children.nodeType);

结果:1
4.4.3在标记里增加一段描述

nodeValue属性:得到(和设置)一个节点的值;

function showpic(whichpic){
var aaaa=whichpic.getAttribute("href");
var iiii=document.getElementById("placeholder");
iiii.setAttribute("src",aaaa);
var text=whichpic.getAttribute("title");
var description=document.getElementById("description");
description.firstChild.nodeValue=text;
//把description对象的第一个子节点的nodeValue属性值设置为变了text的值
// childNodes[0]可写成firstChild;childNodes.length-1可写成lastChild
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: