所以我有一个照片库,其中包含缩略图中的照片和一张大图片。当用户单击缩略图时,它应该显示更大的缩略图图像。其他一切都已完成,但我无法让JS工作。我知道它有点小,所以有人可以看一看,看看我做错了什么吗?提前谢谢。
<html>
<head>
<title></title>
<meta charset = "UTF-8">
<meta http-equiv = "X-UA-Compatible" content = "IE=edge">
<meta name = "viewport" content = "width=device-width, initial-scale = 1">
<link href = "css/bootstrap.min.css" rel = "stylesheet">
<link rel = "stylesheet" href = "html5reset.css">
<link rel = "stylesheet" href = "gallery.css">
</head>
<body>
<div class = "main">
<div class = "wrapper">
<div id = "largeImage">
<img src = "images/machine_1.jpg" alt = "machining image" width = "920" height = "400" id = "bigImage" class = "border"/>
</div>
<div class = "thumbnail">
<img src="images/machine_1.jpg" alt = "machining lathe" id="machine_1"/>
<img src="images/machine_2.jpg" alt = "machining lathe" id="machine_2"/>
<img src="images/machine_3.jpg" alt = "machining lathe" id="machine_3"/>
<img src="images/machine_4.jpg" alt = "machining lathe" id="machine_4"/>
<img src="images/machine_5.jpg" alt = "machining lathe" id="machine_5"/>
<img src="images/machine_6.jpg" alt = "machining lathe" id="machine_6"/>
</div>
</div>
</div>
<script src = "gallery.js"></script>
</body>
</html>
function imgFunction() {
var bigImage = document.getElementById("bigImage");
var thumbnail = document.getElementById("thumbnail");
thumbnail.addEventListener("click",function(event) {
if (event.target.tagName == "IMG") {
bigImage.src = event.target.src;
}
},false);
}
window.addEventListener("load", imgFunction, false);
答案 0 :(得分:3)
我认为您要选择<div class="thumbnail">
,但使用getElementById
。
所以,只需给你的div一个id:<div id="thumbnail">
。
答案 1 :(得分:3)
JQuery Weave: http://kodeweave.sourceforge.net/editor/#3aa0ea4a91d84cfd35f0b8b4151499bc
普通JS编织: http://kodeweave.sourceforge.net/editor/#21d2b4bd5fa4c388d7e63c34ea23f4cd
您的主要问题是您的html中存在document.getElementById("thumbnail")
并且没有#thumbnail
。
所以要么改变......
document.getElementById("thumbnail")
到
document.querySelector(".thumbnail")
或
到
<div id="thumbnail">
var thumbnail = document.querySelector('.thumbnails');
var preview = document.querySelector('.preview');
thumbnail.addEventListener("click", function(e) {
if (e.target.tagName == "IMG") {
preview.src = e.target.src;
}
}, false);
.gallery {
text-align: center;
}
.preview {
width: auto;
max-width: 100%;
}
.thumbnails {
white-space: nowrap;
overflow: auto;
}
.thumbnails img {
cursor: pointer;
height: 70px;
}
<div class="gallery">
<img src="http://www.catersnews.com/wp-content/uploads/2015/06/1_CATERS_BEAR_HANDSHAKE_07-800x498.jpg" class="preview">
<div class="thumbnails">
<img src="http://www.catersnews.com/wp-content/uploads/2015/06/1_CATERS_BEAR_HANDSHAKE_07-800x498.jpg">
<img src="https://s-media-cache-ak0.pinimg.com/736x/9a/44/23/9a4423324fe1fcc23c436a91ad4c9667.jpg">
<img src="http://www.earthtouchnews.com/media/734889/Baby_bears_2014-11-25.jpg">
<img src="http://i.imgur.com/wYFHJNI.jpg">
</div>
</div>