有时候我想通过点击小图片然后使其放大,这样的效果我们是怎么通过JS实现的,下面我为大家讲述DOM和非DOM的解决方案:
主代码(除了JS部分):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片库</title>
<style type="text/css">
*{
padding: 0px;
margin: 0px;
}
a{
text-decoration:none;
}
h1{
text-align: center;
}
li{
float: left;
list-style: none;
}
</style>
</head>
<body>
<h1>Snapshots</h1>
<ul>
<li style="margin-left: 5px; margin-top: 10px;">
<a href="images/2.jpg" title = "灯火" onclick="showPic(this); return false;"><!-- this表示这个对象,当showPic()被调用的时,点击链接,用户还是会被带到图片查看窗口,为了阻止这个默认行为被调用,return false -->
<img style="width: 15%;" src="images/2.jpg">
</a>
</li>
<li style="margin-left: 500px; margin-top: -80px;">
<a href="images/3.jpg" title = "夜空" onclick="showPic(this); return false;">
<img style="width: 25%;" src="images/3.jpg">
</a>
</li>
<li style="margin-left: 1024px; margin-top: -88px;">
<a href="images/4.jpg" title = "城市" onclick="showPic(this); return false;">
<img style="width: 63%;" src="images/4.jpg">
</a>
</li>
</ul><br><br><br><br><br>
<!-- 设置“占位符”图片替换为想要查看的图片,需要通过JS中的setAttribute()改变它的src属性 -->
<img style="width:100%;" id="placeholder" src="images/1.jpg" alt="picture">
<p id="description">Choose an image.</p>
</script>
</body>
</html>
οnclick="showPic(this); return false;"中this指的是当前的对象,即a标签,ruturn false阻止默认行为被触发,即防止点开链接时将用户带到一个新窗口,使得用在“占位符"中打开图片,起到放大图片的效果。
DOM方案:
function showPic(whichPic){
var source = whichPic.getAttribute("href");
//whichPic代表一个元素节点,具体说指向某个图片的<a>元素,getAttribute获得元素节点
var placeholder = document.getElementById("placeholder");
// placeholder.src = source;//与下面一行代码等价,同样可以改变元素属性
placeholder.setAttribute("src", source);//setAttribute对placeholder元素的src属性进行刷新,将属性source值刷新到src里
var text = whichPic.getAttribute("title");//获取属性为title的元素
var description = document.getElementById("description");//得到id是description的p元素,并把它保存到变量description里
description.firstChild.nodeValue = text;//把description对象的第一个叶子节点的nodeValu属性值设置为变量text的值
}
其实上面一段代码也可以简写如下,但由于怕自己一时无法理解,所以还是推荐上述的详细的写法:
function showPic(whichPic){
document.getElementById("placeholder").setAttribute("src", whichPic.getAttribute("href"));
}
通过setAttribute()函数把whichPic.getAttribute("href")从a标签里获得的href属性刷新到img标签里的src属性里,
简单来说setAttribute(attribute, value)实现的把一个属性里面的内容复制并粘贴到另一个属性里;
非DOM实现:
function showPic(whichPic){
var source = whichPic.getAttribute("href");
//whichPic代表一个元素节点,具体说指向某个图片的<a>元素,getAttribute获得元素节点
var placeholder = document.getElementById("placeholder");
placeholder.src = source;//与上面的placeholder.setAttribute("src", source)等价
}
非DOM的方法可移植性不如DOM好,所以更喜欢用DOM的方法。
话不多说,我们看效果图: