Playing a video when clicking on an element of an image.

南楼画角 提交于 2019-12-13 18:06:20

问题


I want to know if it's possible to play a video when you click on an element of an image, and play another video if you click on another element of the same image ?

For instance, imagine a picture of a room : - if I click on the area where the TV set is, the image disappears and video1 starts. - if I click on the chair, same thing but video2 starts instead.

Is this possible using HTML5 and Javascript? If so, how am I going to do that ?

Thanks a lot for reading !


回答1:


Yes, it is possible.

I'm assuming that you have basic understanding of HTML and JavaScript. Also this will only work on browsers that have support for HTML5 and the video element specifically.

First, add a video element to your page

<video id="video" width="600">
  <source type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Then let's assume you have two images, Video 1 and Video 2

<img src="tv.png" id="video1Btn" onclick="loadVideo1()" value="Load Video 1" />
<img src="chair.png" id="video2Btn" onclick="loadVideo2()" value="Load Video 2" />

Once a button is clicked the JavaScript function as in the onclick attribute will be called.

function loadVideo1() {
 var videoEl = document.getElementsByTagName('video')[0];
 var sourceEl = videoEl.getElementsByTagName('source')[0];
 sourceEl.src = 'video1.mp4';
 videoEl.load();
}

function loadVideo2() {
 var videoEl = document.getElementsByTagName('video')[0];
 var sourceEl = videoEl.getElementsByTagName('source')[0];
 sourceEl.src = 'video2.mp4';
 videoEl.load();
}


来源:https://stackoverflow.com/questions/16626673/playing-a-video-when-clicking-on-an-element-of-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!