通过简单的JavaScript 图片库案例来讲解函数应用及扩展。(源代码+素材)
这是一个图片库小页面,通过单击1、2、3、4在原来的页面变换图片和描述。
![img]()
下面是HTML标签:
1 2 3 4 5 6 7 8 9 10 11 12 13
| <body> <h1>Snapshots</h1> <ul> <li><a href="images/1.jpg" onClick="showPic(this); return false;" title="one">1</a></li>
<li><a href="images/2.jpg" onClick="showPic(this); return false;" title="two">2</a></li> <li><a href="images/3.jpg" onClick="showPic(this); return false;" title="three">3</a></li> <li><a href="images/4.jpg" onClick="showPic(this); return false;" title="four">4</a></li> <img src="images/show.jpg" alt="my img gallery" id="placeholder"> </ul> <p id="description">Choose an image.</p> </body>
|
图片变换步骤:1.获取a对象并取得href参数-> 2.获取img 对象-> 3.将href 的参数赋值给img 的src属性。
1 2 3 4 5 6 7 8 9 10 11 12 13
|
showPic(whichpic) function showPic(whichpic){
var source = whichpic.getAttribute("href"); var placeholder = document.getElementById("placeholder"); placeholder.setAttribute("src",source); } 如此一来,就可以变换图片了
|
文本变换如上步骤差不多,但在此前,先了解一下节点
1.childNodes 属性
在一颗节点树上,childNodes属性可以用来获取任何一个元素的所有子元素,它是一个包含这个元素全部子元素的数组:
element.childNodes
1 2 3 4
| function counBodyChildren(){ var body_element = document.getElementsByTagName("body")[0]; alert( body_element.childNodes.length ); }
|
或者你想更清楚的了解childNodes具体是查询了哪个节点,可以尝试一下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <!DOCTYPE html> <html> <body> <p id="demo">请点击按钮来获得 body 元素子节点的相关信息。</p>
<button onclick="myFunction()">试一下</button>
<script> function myFunction() { var txt=""; var c=document.body.childNodes; for (i=0; i<c.length; i++) { txt=txt + c[i].nodeName + "<br>"; }; var x=document.getElementById("demo"); x.innerHTML=txt; } </script>
<p><b>注释:</b>元素中的空格被视为文本,而文本被视为节点。</p>
</body> </html>
|
得到的结果如下:
![img]()
了解节点后继续完善图片库变( showPic(whichpic) )更图片时的描述:
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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; }
|
要分清元素的value属性和nodeValue 不一样,nodeValue适用于“文本节点”和“属性节点”;对应“文档节点”和“标签节点”不起作用。
whichpic.getAttribute("title"); 还有一种写法whichpic.title;
前者只能get 不能赋值,后者可以。whichpic.title = "可赋值";