首页 > 解决方案 > 悬停时可水平滚动的视频库

问题描述

我正在尝试创建一个图像库,当将鼠标悬停在其上时,图像会消失并且视频开始播放,类似于 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 中还有其他图片。我猜这与我尝试将其中的图像绝对定位时丢失我的画廊有关,但是我不确定如何在没有绝对定位它们的情况下实现悬停效果。

标签: javascripthtmljquerycss

解决方案


我们必须解决多个问题。让我们从应该默认显示并在悬停视频时消失的图像开始:

  1. 我们需要一个包含视频和图像的包装元素,例如<div>.
  2. 我们应用于position: relative;父元素(包装器)
  3. 我们应用position: absolute; inset: 0;(inset: 0 = top + right + bottom + left: 0;) 让图像跨越整个包装元素,并以正 z-index 将其逐层提升到视频上方:z-index: 1;
  4. 要在悬停时隐藏图像,我们使用: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>


推荐阅读