如何使用jQuery在悬停时改变图像?

时间:2017-02-10 12:17:20

标签: javascript jquery html frontend

我遇到了这样的问题: 在<div></div>内,总有5张图片,只有1张是可见的,其他4张是隐藏的。

<style>
   #id2, #id3, #id4, #id5 { display: none; }
</style>

<div>
   <img id="id1" src='image.jpg'>
   <img id="id2" src='image.jpg'>
   <img id="id3" src='image.jpg'>
   <img id="id4" src='image.jpg'>
   <img id="id5" src='image.jpg'>
</div>

我的目标是在悬停时以恒定时间戳(例如1秒)更改它们。

$('document').ready(function(){
   $('#1').hover(function(){
      // #id1 hide
      // #id2 show
      // #id2 hide
      // #id3 show
      // #id3 hide
      // #id4 show
      // #id4 hide
      // #id5 show
      // #id5 hide
      // #id1 show
      //  and so on...
   });
});

它将用作视频预览,div和内部图像将从MySQL DB生成。 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

这是一个工作示例,基于我从您的问题中理解的内容:

&#13;
&#13;
$('.preview').hover(function() {
  var $that = $(this),
      toggleFunction = function() {
  	  var $visibleImg = $('img:visible', $that),
          $nextImg = $visibleImg.next('img');
        
      if(!$nextImg.length) {
        $nextImg = $('img:first-child', $visibleImg.parent());
      }
  	
      $nextImg.show().siblings().hide();
    };
	$that.data('interval', window.setInterval(toggleFunction, 1000));
    toggleFunction();
}, function() {
	window.clearInterval($(this).data('interval'));
});
&#13;
.preview img {
  display: none;
}

.preview img:first-child {
  display: block;
}

.preview {
  display: inline-block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preview">
<img src="https://s24.postimg.org/r74b0vcu9/frame_0.gif" />
<img src="https://s24.postimg.org/a7vclm1mp/frame_15.gif" />
<img src="https://s24.postimg.org/600kcv075/frame_30.gif" />
<img src="https://s24.postimg.org/7t82exarl/frame_45.gif" />
<img src="https://s24.postimg.org/5d6912sox/frame_60.gif" />
</div>
&#13;
&#13;
&#13;