HTML How to change image onClick

♀尐吖头ヾ 提交于 2021-02-11 16:44:23

问题


I'm trying to have an image that changes when clicked: when image 1 is clicked, change to image 2, when image 2 is clicked change to image 3 and when image 3 is clicked it changes to image 1.

<p>
    <img alt="" src="assets/img1.png" 
        style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()"   />

<script language="javascript">
function changeImage() {

    if (document.getElementById("imgClickAndChange").src == "assets/img1.png") 
    {
        document.getElementById("imgClickAndChange").src = "assets/img2.png";

    }
    else if (document.getElementById("imgClickAndChange").src == "assets/img2.png")
    {
        document.getElementById("imgClickAndChange").src = "assets/img3.png";

    }
    else if(document.getElementById("imgClickAndChange").src == "assets/img3.png"){
    document.getElementById("imgClickAndChange").src = "assets/img1.png"

    }

回答1:


Clean and optimal solution in my opinion. As the users before said. It is good to use array to held the images paths.

var images = ["https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350", "https://i2.wp.com/beebom.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg?resize=640%2C426", "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350"]

var imgState = 0;

var imgTag = document.getElementById("imgClickAndChange");

imgTag.addEventListener("click", function (event) {
  imgState = (++imgState % images.length);
  event.target.src = images[imgState];
});

Solution




回答2:


There were a lot of syntax errors in your code. I cleaned them up in a codepen here where you can see that your basic logic was correct. Though, as other users pointed out, there are more elegant ways to solve this problem.

https://codepen.io/anon/pen/MPYgxM

HTML:

<p>
    <img alt="" src="https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg" 
        style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()"   />
        </p>

JS:

function changeImage() {

    if (document.getElementById("imgClickAndChange").src == "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg") 
    {
        document.getElementById("imgClickAndChange").src = "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg";

    }
    else if (document.getElementById("imgClickAndChange").src == "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg")
    {
        document.getElementById("imgClickAndChange").src = "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg";

    }
    else if(document.getElementById("imgClickAndChange").src == "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg"){
    document.getElementById("imgClickAndChange").src = "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg"

    }
}



回答3:


you can increment value on each click and update img. on base of incremented value

 <img alt="" src="assets/img1.png" style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()"   />

   <script language="javascript">
        var counter = 1;
        function changeImage() {
            counter > 3 ? counter = 1 : counter++; 
            document.getElementById("imgClickAndChange").src = "assets/img"+counter+".png";
        }

    </script>



回答4:


Hi this is different approach.
new ClickListener() is the class used to handle your logic & dom logic

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Image click</title>
  </head>
  <body>
    <div id="player">
    </div>

    <script>
      class ClickListener {
        constructor() {
          this.rootElement = document.querySelector( "#player" );
          this.element = document.createElement("img");
          this.rootElement.appendChild(this.element);
          this.images = ['./1.jpg', './2.jpg', './3.jpg']
          this.idx = 0
          this.init()
        }

        init() {
          this.element.src = this.images[this.idx]
          this.element.style.width = `400px`;
          this.element.style.height = `400px`;
          this.element.onclick = this.nextImage.bind(this)
        }

        nextImage() {
          this.idx++;
          if(this.idx >= this.images.length) {
            this.idx = 0;
          }
          this.element.src = this.images[this.idx]
        }

      }
      new ClickListener()
    </script>
  </body>
</html>


来源:https://stackoverflow.com/questions/52561727/html-how-to-change-image-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!