简单图片库

来源:互联网 发布:淘宝买奢侈品 编辑:程序博客网 时间:2024/06/05 01:12

1.准备几张图片
index.html文件

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <h1>MyPictures</h1>        <ul>            <li>                <a href="img/one.png" title="one">one</a>            </li>            <li>                <a href="img/two.png" title="two">two</a>            </li>            <li>                <a href="img/three.jpg" title="three">three</a>            </li>            <li>                <a href="img/four.jpg" title="four">four</a>            </li>        </ul>        <img src="img/one.png" id="place" title="one"/>    </body>

效果图:
这里写图片描述

我们要考虑的是通过点击one、two……将img里的图片换成相对应的,那如何实现呢?
每次点击的时候讲img里的src属性换成相对应的就可以了。
为元素动态设置属性需要调用getAttribute和setAttribute
我们写一个函数实现上述功能:

function showPic(whichPic)

函数的参数是一个元素节点,就是将li中的a元素节点传进来,获得href属性:

whichPic.getAttribute("href");

将这个路径存入一个变量:

var source = whichPic.getAttribute("href");

接下来就是获取img图片:

var place = document.getElementById("place");

后面就可以将img里的src属性动态替换:

place.setAttribute("src",source);

代码清单:

function showPic(whichPic){    var source = whichPic.getAttribute("href");    var place = document.getElementById("place");    place.setAttribute("src",source);}

下面就是事件处理:
showPic()需要一个参数,一个带有href的元素节点,使用this这个关键字,具体到当前例子,this表示元素节点。

onclick = "showPic(this)"

如果仅仅将这个函数放到列表中,还是有问题的,点击这个连接时,连接被点击的默认行为也会被触发。这意味着用户还是会被带到图片查看窗口,这是我们不希望发生的。
解决方法:添加return false;

<a href="img/one.png" title="one" onclick="showpic(this);return false;">one</a>

这样就可以了

0 0