简体   繁体   中英

How can I change an image when I click on another image? (Without onclick)

I´m doing a landing page and wanted to make the main image change when I click on other images. I´ve tried with this

<div class="thumb">
  <ul>
    <li> 
      <img id="img1" class="smallImg coupe" src="./assets/smallCar1.png" alt="small img">
    </li>
  </ul>
  <ul>
    <li>
      <img id="img2" class="smallImg" src="./assets/smallCar2.png" alt="small img">
    </li>
  </ul>
  <ul>
    <li>
      <img id="img3" class="smallImg" src="./assets/smallCar3.png" alt="small img">
    </li>
  </ul>
</div>
function imageChange() {
  let picDefault = document.getElementById("img");

  if ((picDefault = "img")) {
    picDefault.src = "./assets/img1.png";
  }
}
picDefault.addEventListener(click, imageChange);

Sample code for updating an image by clicking on another image. Use case might be completely different.

 const thumps = document.getElementsByClassName("thump"); // secondary images const main = document.getElementById("main"); for(let i = 0; i < thumps.length; i ++) { const el = thumps[i] el.addEventListener("click", function(e) { // add click handler const elem = e.target; main.src = elem.src; }) }
 #main { max-width: 300px; }.thump { width: 100px; margin: 4px; padding: 2px; border: 1px solid #ccc; display: inline-block; }
 <div> <h5>Main Image</h5> <img src="https://images.unsplash.com/photo-1644243019151-0bb97ce1af84" id="main"/> </div> <h5>Click Images below thumpnails to update main image</h5> <div class="row"> <img src="https://images.unsplash.com/photo-1644235279538-4cc7cbdca6a8" class="thump"> <img src="https://images.unsplash.com/photo-1643443026948-c17b9bb16758" class="thump"> <img src="https://images.unsplash.com/photo-1644243019151-0bb97ce1af84" class="thump"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM