gpt4 book ai didi

javascript - 使用javascript单击图像时如何播放数组中的每个视频?

转载 作者:行者123 更新时间:2023-12-02 23:27:44 24 4
gpt4 key购买 nike

我有两个数组。一个是视频,一个是图像。单击图像时,我一次只需要播放一个视频。就像如果单击 img[1] 则应播放视频[1],如果单击 img[2] 则应播放视频[2]。

我需要做这样的事情:IMAGE

我已经浏览了一些示例,但没有找到仅使用 javascript 的任何类似答案。现在,当我单击图像时,它会打开我添加用于测试但无法播放视频的 anchor 标记链接。

  var videosList = [
"http://media.w3.org/2010/05/sintel/trailer.mp4",
"http://media.w3.org/2010/05/bunny/trailer.mp4",
"http://vjs.zencdn.net/v/oceans.mp4"
];

var allVideos = videosList.length;
var i = 0;
for (; i < allVideos; i++) {
var vid = document.createElement('source');
vid.src = videosList[i];
document.getElementById('myVideo').appendChild(vid);
}



var images = [
'https://picsum.photos/200/300',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300?grayscale',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300'

];

var allPics = images.length;
var i = 0;

for (; i < allPics; i++) {
var a = document.createElement('a');
a.href = 'example.html';
var img = document.createElement('img');
img.src = images[i];
a.appendChild(img);
document.getElementById('myImg').appendChild(a);
}

这里是运行代码作为示例:codepen

最佳答案

// JavaScript can be change in the following way
// Assuming that the video to be played is the same as index of the image clicked



// make it as global to access in all functions
var videosList = [
"http://media.w3.org/2010/05/sintel/trailer.mp4",
"http://media.w3.org/2010/05/bunny/trailer.mp4",
"http://media.w3.org/2010/05/bunny/movie.mp4",
"http://vjs.zencdn.net/v/oceans.mp4"
];
window.onload = function() {
// for videos
var vid = document.createElement('source');
vid.src = videosList[0]; // playing first video in the array by default
document.getElementById('myVideo').appendChild(vid);


// for images

var images = [
'https://picsum.photos/200/300',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300?grayscale',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300'

];

var allPics = images.length;
var i = 0;

for (; i < allPics; i++) {
var a = document.createElement('a');
// a.href = 'example.html';
var img = document.createElement('img');
img.src = images[i];
img.id = i; // for the reference of clicked image
a.appendChild(img);
a.addEventListener("click", clickFn, false);
document.getElementById('myImg').appendChild(a);
}

}

/**click function for the image of the image */
clickFn = function(e){
var video = document.getElementById('myVideo');
video.src = videosList[parseInt(e.srcElement.id,10)];
video.play();
}

希望有帮助..!!

修改codepen中的代码

关于javascript - 使用javascript单击图像时如何播放数组中的每个视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com