javascript - 悬停时可水平滚动的视频库
问题描述
我正在尝试创建一个图像库,当将鼠标悬停在其上时,图像会消失并且视频开始播放,类似于 Netflix。我能够在这里创建一个做我想做的画廊:
.container {
display: flex;
overflow-x: auto;
width: 600px;
margin-left: 300px;
}
.container img {
margin-right: 15px;
width: 150px
}
<div class="container">
<img src=https://image.shutterstock.com/image-vector/check-back-soon-hand-lettering-600w-1379832464.jpg>
以及我想要的图像消失和悬停视频播放:
const videos = document.querySelectorAll(".polystar");
for (const video of videos) {
video.addEventListener('mouseover', function() {
video.play()
}, false);
video.addEventListener('mouseout', function() {
video.pause()
}, false);
}
.gallery-cv {
display: flex;
z-index: 1;
overflow-x: auto;
width: 1200px;
margin: 0;
}
.polystar {
width: 300px;
z-index: 2;
opacity: 0;
}
.top-img {
position: absolute;
width: 300px;
height: 535px;
z-index: 1;
}
.polystar:hover {
opacity: 1;
}
.second {
margin-left: 150px;
position: absolute;
z-index: 3;
}
<h1> headline </h1>
<div class="gallery-cv">
<img class="top-img first" src="https://source.unsplash.com/random">
<video class='polystar' muted src="https://player.vimeo.com/external/432406907.hd.mp4?s=f35b5f202d573efa75d9293d213fc3be0927fd85&profile_id=172&oauth2_token_id=57447761" type="video/mp4">
<img class="top-img second" src="https://source.unsplash.com/random">
<img class="top-img third" src="https://source.unsplash.com/random">
</div>
但是当我尝试组合这些(正如我在上面的代码笔中尝试过的那样)时,我的画廊消失了,我只剩下一张图片,尽管 html 中还有其他图片。我猜这与我尝试将其中的图像绝对定位时丢失我的画廊有关,但是我不确定如何在没有绝对定位它们的情况下实现悬停效果。
解决方案
我们必须解决多个问题。让我们从应该默认显示并在悬停视频时消失的图像开始:
- 我们需要一个包含视频和图像的包装元素,例如
<div>
. - 我们应用于
position: relative;
父元素(包装器) - 我们应用
position: absolute; inset: 0;
(inset: 0 = top + right + bottom + left: 0;) 让图像跨越整个包装元素,并以正 z-index 将其逐层提升到视频上方:z-index: 1;
- 要在悬停时隐藏图像,我们使用:
div:hover img { display: none; }
下一个问题是在悬停时开始播放视频。为此,我们需要 JS,我们也可以使用onmouseover
-attribute:onmouseover="element.play();"
要在您不悬停时暂停视频,我们可以使用 JS 或onmouseout
-attribute:onmouseout="element.pause();"
onmouseover
和触发器/属性都onmouseout
必须添加到包装父元素。
div {
position: relative;
}
video {
width: 100%;
}
img {
width: 100%;
object-fit: cover;
position: absolute;
inset: 0;
z-index: 1;
}
div:hover img {
display: none;
}
<div onmouseover="document.querySelector('video').play();" onmouseout="document.querySelector('video').pause();">
<video>
<source src="https://www.tacoshy.de/stackoverflow/testvideo.mp4" type="video/mp4">
</video>
<img src="https://via.placeholder.com/1920x1080.jpg">
</div>
推荐阅读
- ios - 找不到-lCocoaAsyncSocket clang 的库:错误:链接器命令失败,退出代码为 1
- sml - 如何将 Real 转换为 Int?
- mysql - 选择5公里内的记录,分组依据
- kubernetes - Kubernetes Pod 的非本地通信
- java - 递归地反转 Char 的 LinkedLists 的 LinkedList
- cron - 第一次取消暂停时如何停止气流运行任务?
- spring - 如何为feign客户端实现状态检查?
- azure - 如何确保 Azure Dev Ops Pipeline 中的代理具有对存储帐户的防火墙访问权限?
- amazon-web-services - 是否有可能多个实例运行一个 SQS 队列?
- vim - vimrc 中的折叠设置在 vimwiki 中不起作用