jQuery视频在mouseenter功能上的延迟

时间:2018-09-08 00:15:14

标签: javascript jquery mouseevent delay

我有一个视频缩略图效果,当用户将鼠标悬停在图片上时,视频就会显示并开始播放。效果很好,但是当我尝试应用延迟方法来显示视频时,它无法正常工作。

$(document).on('mouseenter', '.img-video', function(e) {
    $(this).hide();
  $(this).next().trigger('play').show();

  $(this).next().mouseout(function() {
        $(this).hide().trigger('pause')[0].currentTime = 0;
    $(this).prev().show();
    });
})

JSFiddle示例在这里https://jsfiddle.net/aq9Laaew/204575/

谢谢您的建议

1 个答案:

答案 0 :(得分:1)

如果悬停速度非常快,请使用命名的Timeout函数并将其清除。如果悬停时间较长,则显示视频。

$(document).on('mouseenter', '.img-video', function(e) {
  var image = $(this);
  
  var imageTimer = window.setTimeout(function() {
    image.data('imageTimer', null);
    image.hide();
    image.next().trigger('play').show();
  }, 2000);
  image.data('imageTimer', imageTimer);

  image.next().mouseout(function() {
    image.next().hide().trigger('pause')[0].currentTime = 0;
    image.show();
  });
});

$(document).on('mouseleave', '.img-video', function(e) {
  var image = $(this);
  var imageTimer = $(this).data('imageTimer');
  if (imageTimer !== null) {
      window.clearTimeout(imageTimer);
  }
});
.container {
  margin-top: 20px;
}

.sample {
  display:none;
}

.col{
  position:relative;
}
.sample{
      position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    object-fit: fill;
    z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class="col">
      <img class="img-video"  src="https://usclub.kz/temp/mcu/3.jpg" width="320" height="200"/>
       <video class="sample" muted="muted" preload loop>
         <source src="https://www.lvmagnet.com/wp-content/uploads/2017/01/video-bg.mp4" type="video/mp4">
         No video support
       </video>
    </div>
    <div class="col">
      <img class="img-video" src="https://usclub.kz/temp/mcu/1.jpg" width="320" height="200"/>
       <video class="sample" muted="muted" preload loop>
         <source src="https://www.lvmagnet.com/wp-content/uploads/2017/01/video-bg.mp4" type="video/mp4">
         No video support
       </video>
    </div>
</div>