将鼠标悬停在缩略图上会使用JavaScript中的YouTube API触发音频而不是视频-我该如何解决这个问题?

2hh7jdfx  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(127)

当我悬停在缩略图上时,我试图播放YouTube视频,但它只播放音频,我看不到视频,当我停止悬停时,它不会停止播放。
下面是代码
HTML

<div class="thumbnail" data-video-id="D9N7QaIOkG8">
    <img src="assets\meyra.jpg" alt="Thumbnail 1">
    <div class="video-overlay"></div>
</div>

<script>
  function onYouTubeIframeAPIReady() {
    const thumbnails = document.querySelectorAll(".thumbnail");

    thumbnails.forEach(function(thumbnail) {
      const videoOverlay = thumbnail.querySelector(".video-overlay");
      const videoId = thumbnail.dataset.videoId;

      thumbnail.addEventListener("mouseenter", function() {
        const player = new YT.Player(videoOverlay, {
          videoId: videoId,
          width: "100%",
          height: "100%",
          playerVars: {
            autoplay: 1,
            controls: 0,
            rel: 0,
            showinfo: 0
          }
        });

        videoOverlay.style.display = "block";
      });

      thumbnail.addEventListener("mouseleave", function() {
        videoOverlay.innerHTML = "";
        videoOverlay.style.display = "none";
      });
    });
  }
</script>

我想要一个视频来掩盖缩略图就像在youtube预览时,我悬停和停止播放时,鼠标停止悬停。

j9per5c4

j9per5c41#

问题是,一旦你鼠标悬停,youtube就会用iframe替换你的**.videoOverlaydiv。因此,您在videoOverlay**变量中选择的引用将不再适用于显示和隐藏。
你需要更换

videoOverlay.style.display = "block";

this.querySelector('.video-overlay').style.display = "block";

在mouseleave事件处理程序中执行相同的操作

this.querySelector('.video-overlay').innerHTML = "";
this.querySelector('.video-overlay').style.display = "none";

编辑:要与视频对象交互,(比如你需要播放或停止视频),那么你需要像下面这样获取播放器的引用。

function onYouTubeIframeAPIReady() {
  const thumbnails = document.querySelectorAll(".thumbnail");

  var player;
  thumbnails.forEach(function(thumbnail) {
    const videoOverlay = thumbnail.querySelector(".video-overlay");
    const videoId = thumbnail.dataset.videoId;

    thumbnail.addEventListener("mouseenter", function() {
      player = new YT.Player(videoOverlay, {
        videoId: videoId,
        width: "100%",
        height: "100%",
        playerVars: {
          autoplay: 1,
          controls: 0,
          rel: 0,
          showinfo: 0
        }
      });

      this.querySelector('.video-overlay').style.display = "block";
    });

    thumbnail.addEventListener("mouseleave", function() {
      this.querySelector('.video-overlay').innerHTML = "";
      this.querySelector('.video-overlay').style.display = "none";
      player.destroy();
    });
  });
}

相关问题