简体   繁体   中英

Toggling image onclick event inline

Managed with the snippet below to change from the first image to the second image using the inline onclick javascript event. My question is; is there a way to change the second image back to first image when clicking on the second image with another inline Javascript event? ie. without writing a function.

<img class="first-image" src="/first-image.png" onclick="this.src=\\'/second-image.png\\'" alt="my images">

You can update your code like this:

<img class="first-image" src="/first-image.png" onclick="this.src==='/first-image.png' ? this.src='/second-image.png' : this.src='/first-image.png'" alt="my images">

Here is a working example:

 <img class="first-image" src="https://photo-works.net/images/europe-landscape-photo-edited.jpg" onclick="this.src==='https://photo-works.net/images/europe-landscape-photo-edited.jpg' ? this.src='https://thumbs.dreamstime.com/b/landscape-nature-mountan-alps-rainbow-76824355.jpg' : this.src='https://photo-works.net/images/europe-landscape-photo-edited.jpg'" alt="my images">

You could store both urls as properties of image tag, like this:

<img
  src="/first-image.png"
  data-src-1="/first-image.png"
  data-src-2="/second-image.png"
  onclick="this.src = this.src === this.getAttribute('data-src-1') ? this.getAttribute('data-src-2') : this.getAttribute('data-src-1')"
/>

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