when mouse over image slide is start as gif image

2019-08-23 09:06发布

问题:

I have 5 images in a same folder. 1.jpg,2.jpg,3.jpg,4.jpg,5.jpg I will be show only one image on my webpage. example

<body>
<img src="1.jpg">
</body>

when visitor is mouse over on image, image will be change to 2.jpg and,3.jpg and....will be stop at 5.jpg.Slideshow is similar as a gif image.
Please How to write javascript or jquery .
Please tell me simplest way.
Thank my dear friend.
I found simalor question in this website.But I can't found complete answer for me.
If this question is duplicate, so sorry
please forgive me for my poor english useage.

回答1:

You can use jQuery's hover event and pass in the onenter and onout methods. On enter you can call and setup an interval to increment the number of your image, and on out you want to stop it by clearing your interval.

<!DOCTYPE html>
<html>
  <head>
    <title>image</title>        
  </head>
  <body>

    <img id="img" src="1.jpg" />

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      var interval = null;
      function changeImage(){
        var nextNum = parseInt($('#img').attr('src').replace('.jpg',''), 10) + 1;
        // If you want it to repeat back to 1 after 5
        nextNum = nextNum > 5 ? 1 : nextNum;
        $('#img').attr('src', nextNum+'.jpg');
      }

      $('#img').hover(
        function(){
          // Call change Image every 50ms
          interval = setInterval(changeImage, 50);
          changeImage();
        },
        function(){
          // Stop the call
          interval && clearInterval(interval);
        }
      );
    </script>
  </body>
</html>​​​​​​​​​​​​