JavaScript - 仅通过addEventListener单击缩略图来更改预览图像

问题描述 投票:0回答:2

我正在尝试创建一个非常简单,纯粹的JavaScript图库,在点击较小的图像缩略图时,它会将较大的预览图像更改为您刚刚单击的缩略图。

我是JavaScript新手,我一直在试验它。我也试图避免在HTML中使用onClick,因为我被告知这是不好的做法。所以我发现使用addEventListener似乎是另一种方法。

唯一的问题是,我不知道该怎么做。大多数其他教程使用的onClick函数并不理想。

我想知道是否有人可以帮助甚至提供一些其他来源给我一个开始。

这是HTML和我在JavaScript的开始:

HTML

<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
  }

})();
javascript html image addeventlistener image-gallery
2个回答
1
投票
(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;
  }
})();

2
投票

不要在JavaScript变量名中使用连字符。破折号用于减法。您可以在类名和元素ID中使用短划线,但不能在JavaScript变量名中使用短划线。

您的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(){}。您将需要包含带有<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; 
  }
© www.soinside.com 2019 - 2024. All rights reserved.