簡體   English   中英

如何使用香草JavaScript更改點擊圖片

[英]How to change an image on click using vanilla JavaScript

我是編程新手,目前正在學習DOM操作。 我將不勝感激。

我需要將主圖片更改為用戶單擊的任何圖片。 我只想使用JavaScript。

我遇到的主要問題是我不知道如何從單擊的圖像中提取src屬性。

 let pics = document.querySelectorAll('.thumbnail'); let pic = document.querySelector('.hero img'); pics.addEventListener('click', function(){ pic = pics.src; }) 
 <main role="main"> <h1>Image Carousel</h1> <div class="hero"> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat1.jpg" alt="An orange-eyed grey cat stretches toward the camera."/> </div> <div class="thumbnails"> <a class="thumbnail" href="#"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat1.jpg" alt="An orange-eyed grey cat stretches toward the camera."/></a> <a class="thumbnail" href="#"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat2.jpg" alt="Closeup of a blue-eyed, grey cat with markings."/></a> <a class="thumbnail" href="#"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat3.jpg" alt="An orange cat licks its paw."/></a> <a class="thumbnail" href="#"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat4.jpg" alt="A content brown cat lounges with eyes closed."/></a> </div> </main> 

您必須獲取數組中的所有圖像,迭代該數組,並在每個圖像中添加一個事件偵聽器 ,以獲取src屬性

 let image = document.querySelectorAll('img'); // This is going to return you an array with all the images you have in the document // here we're iterating that array for(let i = 0; i < image.length; i++) { // Here is like selecting each of those items and adding an event listener image[i].addEventListener('click', (e) => { // When you click at the image you will get in console the link of that image console.log(e.target.src); }); } 
  <main role="main"> <h1>Image Carousel</h1> <div class="hero"> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat1.jpg" alt="An orange-eyed grey cat stretches toward the camera."/> </div> <div class="thumbnails"> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat1.jpg" alt="An orange-eyed grey cat stretches toward the camera."/> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat2.jpg" alt="Closeup of a blue-eyed, grey cat with markings."/> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat3.jpg" alt="An orange cat licks its paw."/> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat4.jpg" alt="A content brown cat lounges with eyes closed."/> </div> </main> 

不幸的是,您不能在元素數組上設置事件偵聽器。 您需要遍歷所有這些對象並設置偵聽器。

let pics = document.querySelectorAll('.thumbnail');
let pic = document.querySelector('.hero img');
for( let x = 0; x <  pics.length; x++ ){
  pics.item( x ).addEventListener('click', function( event ){
    pic.src = this.getElementsByTagName('img')[0].src;
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM