我正在尝试创建一个非常简单的纯JavaScript图片库,在这里单击一个较小的图像缩略图,它会将较大的预览图像更改为您刚才单击的缩略图。
我是JavaScript的新手,我一直在尝试它。我还试图避免在HTML中使用onClick,因为有人告诉我这是不好的做法。因此,我发现使用addEventListener似乎是另一种方法。
唯一的问题是,我不知道该怎么处理它。大多数其他教程都使用onClick函数,这并不理想。
我想知道是否有人能帮我,甚至提供一些其他的消息来源给我一个开始。
下面是HTML和我在JavaScript的起点:
<section class="image-gallery">
<h4>IMAGE GALLERY</h4>
<section id="gallery-preview">
<img src="images/gallery1.png" alt="image-gallery-1">
</section>
<section id="gallery-thumbnails">
<img src="images/gallery1.png" alt="image-gallery-1">
<img src="images/gallery2.png" alt="image-gallery-2">
<img src="images/gallery3.png" alt="image-gallery-3">
<img src="images/gallery4.png" alt="image-gallery-4">
<img src="images/gallery5.png" alt="image-gallery-5">
</section>
</section>JavaScript
(function(){
let image-preview = document.getElementById("gallery-preview");
let image-thumbnail = document.getElementById("gallery-thumbnails");
image-thumbnail.addEventListener("click", imageChanger);
function imageChanger()
{
//something here
}
})();发布于 2017-12-26 15:09:50
(function(){
let imagePreview = document.querySelector("#gallery-preview img");
let imageThumbnail = document.getElementById("gallery-thumbnails");
imageThumbnail.addEventListener("click", imageChanger);
function imageChanger(e) {
imagePreview.src = e.target.src;
}
})();发布于 2017-12-26 15:19:21
不要在JavaScript变量名中使用连字符。破折号是用来减法的。您可以在类名和元素id中使用破折号,但不能将其用作JavaScript变量 names 。
您的html需要一个用于所有图像的类。
<section id="gallery-thumbnails">
<img class="my-images" src="images/gallery1.png" alt="image-gallery-1">
<img class="my-images" src="images/gallery2.png" alt="image-gallery-2">
<img class="my-images" src="images/gallery3.png" alt="image-gallery-3">
<img class="my-images" src="images/gallery4.png" alt="image-gallery-4">
<img class="my-images" src="images/gallery5.png" alt="image-gallery-5">
</section> 接下来,您的JavaScript异步运行。你得明白这一点。这意味着在加载所有html之前,不应该尝试运行"imageChanger()“函数。如果html仍然在加载,当您的函数试图将eventListener附加到它时,其中一些可能不存在。
通过异步,它意味着JavaScript运行,不会等待很长的进程在执行下一行代码之前完成。您可以快速完成一些事情,比如添加几个数字,但是当您从服务器抓取数据并以html页面表示数据时,这些事情需要时间。您需要确保只在上工作,已经准备好了。
要确保加载html,请查看jquery的$(document).ready() {}。要使用Jquery,您需要包含一个带有<script>标记的Jquery。
$(document).ready() {
let myImages = document.getElementsByClassName("my-image");
// You have more than one image in myImages.
for (i = 0; i < myImages.length; i++) {
myImages.addEventListener("click", imageChanger);
}
}
// Notice this function is **outside** of document.ready.
// You need the function immediately available.
function imageChanger()
{
// "this" is the element you clicked.
this.style.height = 100px;
this.style.width = 100px;
}https://stackoverflow.com/questions/47980232
复制相似问题