点击嵌入自定义动画缩略图叠加的 YouTube 视频时出现小故障

Small glitch when clicking YouTube video embed with custom, animated thumbnail overlay

提问人:Jason O 提问时间:4/4/2023 更新时间:4/4/2023 访问量:42

问:

我正在处理的 YouTube 视频嵌入遇到了一些问题,该视频顶部有一个可点击的动画占位符图像。我能够单击缩略图以正常启动视频,但是有一个小故障,您可以在视频开始播放之前短暂地看到带有YouTube按钮的静止图像。

有没有办法防止在视频开始时显示带有按钮的现有视频缩略图?我只想隐藏缩略图并立即显示正在播放的视频,而不会首先出现视频缩略图故障。下面是一个代码示例来说明基本问题:

// Used with the YouTube videos which have thumbnail images to start the video
function playButtonClicked(playButton) {
    // Get reference to the youtube video iFrame
    let video = playButton.nextElementSibling;

    // Start the video
    video.setAttribute("src", video.getAttribute("src") + "&autoplay=1");

    // Hide the thumbmnail and play button icon
    let thumbnail = playButton.previousElementSibling;
    thumbnail.style.visibility = "hidden";
    playButton.style.visibility = "hidden";
}

var video = document.querySelector(".small_video_container");
var aspectRatio = Number(video.getAttribute("data-aspectRatio"));
var height = video.getBoundingClientRect().width / aspectRatio;
video.getBoundingClientRect().height = height;
video.style.height = height + "px";
.small_video_container {
    height: 100%;
    width: 100%;
}

.video {
    height: 100% !important;
    width: 100% !important;
    display: block;
}

.video-thumbnail {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.play-button {
    position: absolute;
    top: 50%;
    left: 50%;
    height: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
}
<div class="small_video_container" align="center" data-aspectRatio="1.7777">
    <img class="video-thumbnail" src="https://www.staging7.midstory.org/wp-content/uploads/2023/03/animated-background.gif" alt="Video Thumbnail">
    <img class="play-button" onclick="playButtonClicked(this)" src="https://www.staging7.midstory.org/wp-content/uploads/2023/03/play-icon.png" alt="Play Video">
    <iframe class="video" loading="lazy" src="https://www.youtube.com/embed/nfDkietqdPY?showinfo=0&controls=0&autohide=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

注意:由于某种原因,YouTube 视频不会在代码片段中播放,但它可以在真实网站上播放。下面是一个 codePen,其中也有相同的示例:

https://codepen.io/Jdo300/pen/PoyYzNq

注2:当您在CodePen中单击要播放的视频时,它有时会启动,然后在一瞬间停止。这也不会发生在真实网站上,但你将能够看到我在那里谈论的故障。

javascript html css, youtube 视频嵌入

评论


答: 暂无答案