javascript - 鼠标输入功能上的jQuery视频延迟
问题描述
我有一个视频缩略图效果,当用户将鼠标悬停在图片上时,视频显示并开始播放。它工作得很好,但是当我尝试应用延迟方法来显示视频时,它不能正常工作。
$(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/
谢谢你的任何建议
解决方案
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>
推荐阅读
- amazon-web-services - AWS Athena:删除日期范围之间的分区
- angular - includedByState & 包含过滤器不适用于 ngClass
- android - 在 Flutter 应用中添加对 Android 支持的支持后,Gradle Sync 失败
- java - 有没有办法使用 jOOQ 动态获取所有表字段名称?
- java - Base64 不对整个字符串进行编码
- piranha-cms - Piranha CMS:如何查找页面的子页面
- python - Tensorflow 无法将字符串转换为数字
- java - IntelliJ:自定义自动更正/完成条目
- java - Linux IntelliJ Chrome WebDriverManager“chrome(或任何其他浏览器)无法启动”
- c++11 - 如何将 std::unordered_set 用于向量
> 删除重复项