【问题标题】:Hover image, play certain video悬停图片,播放特定视频
【发布时间】:2020-04-02 00:04:59
【问题描述】:

首先,我对 Javascript 很陌生,但也涉足了一点,在互联网上观看视频。

我有一些图像,我想用作触发对象来播放与它们对应的视频。假设我有 3 张图片。 img1 (vid1) img2 (vid2) img3 (vid3)。如果我将鼠标悬停在其中一张图像上方,则播放与其对应的图像。 (我显然需要在我的视频 src 中引用不同的视频)

我可以悬停并播放单个视频,但不确定如何拥有多个可以加载和播放到 html 视频中的源。

HTML:

<div class = "videoContainer"> 
    <video id="video" src="Videos/Glitch.mp4" height = "180">
    <div class ="body">        
        <div class = "textPresets">   
            <input class ="glitch" type = "image" src ="Pics/Glitch.png" onmouseover="playVideo()" onmouseout ="pauseVideo()">

            <div class="line"></div>

            <input class ="gold" type = "image" src ="Pics/Golden-Text_Preview.png" onmouseover="playVideo()" onmouseout = "pauseVideo()">

            <div class="line"></div>

            <input class ="chrome" type = "image" src ="Pics/Chrome-Text_Preview.png" onmouseover="playVideo()" onmouseout = "pauseVideo()">
        </div> 
    </div>
</div>       

JAVASCRIPT:

var myVideo = document.getElementById("video");
function playVideo() { 
    myVideo.play(); 
} 
function pauseVideo() { 
    myVideo.pause(); 
} 

非常感谢!

【问题讨论】:

  • 澄清一下,无论您将鼠标悬停在哪个图像上,您都想播放同一组视频吗?

标签: javascript html


【解决方案1】:

您可以在每个图像输入控件上使用 html 中的数据属性,其中包含您要播放的视频源。

数据属性由您定义,因此您可以使用data-video-src="video.mp4" 之类的内容。我不知道其他视频的文件名,但根据您的示例,我假设它们与图像文件名相同。您还必须在 onmouseover 事件上使用 this 传递对控件的引用,因此它将更改为 onmouseover="playVideo(this);

<video id="video" height="180">

<input class="glitch" type="image" src="Pics/Glitch.png" data-video-src="Videos/Glitch.mp4" onmouseover="playVideo(this)" onmouseout="pauseVideo()">
<input class="gold" type="image" src="Pics/Golden-Text_Preview.png" data-video-src="Videos/Golden-Text_Preview.mp4" onmouseover="playVideo(this)" onmouseout="pauseVideo()">
<input class="chrome" type="image" src="Pics/Chrome-Text_Preview.png" data-video-src="Videos/Chrome-Text_Preview.mp4" onmouseover="playVideo(this)" onmouseout="pauseVideo()">

然后根据每个图像的数据属性更改javascript以使用视频源

var myVideo = document.getElementById("video");

function playVideo(elem) {

    // get the data attribute with the video source
    // note that 'elem' is a reference to the specific control you are mousing over
    var videoSource = elem.getAttribute('data-video-src');

    // update the video control with the video source for this image
    myVideo.setAttribute('src', videoSource);

    // play the video
    myVideo.play(); 
} 

function pauseVideo() { 
    myVideo.pause(); 
} 

祝你好运!如果您有任何问题或需要澄清,请发表评论

【讨论】:

  • 还有一个问题。有没有办法将视频设置回视频的开头而不是暂停?
  • @chimchase 看起来在视频对象上有一个currentTime 属性,如此处所述stackoverflow.com/a/10461709/8678978 我尚未对此进行测试,但看起来它可以解决问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 2018-11-27
  • 2021-03-13
  • 1970-01-01
  • 2020-07-22
  • 2015-03-11
  • 1970-01-01
相关资源
最近更新 更多