如何使用javascript读取视频路径并将其传递给html源值。目前,我正在使用从html进行硬编码来读取视频,并且希望它能够动态转换为javascript。这是我从项目中的内容文件夹中临时加载的内容:
<video id="video" controls preload="metadata" style="width:100%; height:100%">
<source src="~/Content/Videos/Sample_Vid.mp4" type="video/mp4">
</video>
答案 0 :(得分:0)
如果我正确理解了您的问题,那么您可以:
实现类似于setVideoSource()
的功能,如下所示,该功能可让您设置/更改页面中已经存在的视频元素的来源,或者
实现类似于addVideo()
的功能,如下所示,该功能可让您使用自己选择的来源向页面动态创建/添加新的视频元素
有关这两个功能如何工作的详细信息,请参见以下文档:
/*
Updates the source of first video in the document matching the selector
*/
function setVideoSource(selector, src) {
const element = document.querySelector(selector);
/*
Check that element is video before proceeding
*/
if(element.nodeName === 'VIDEO') {
/*
If element is a video, remove any source children if present
*/
for(const source of element.querySelectorAll('source')) {
element.removeChild(source);
}
/*
Create a new source element and populate it with the src
attribute
*/
const source = document.createElement('source');
source.setAttribute('src', src);
/*
Add source element to the video we're updating
*/
element.appendChild(source);
}
}
/*
Adds a new video to the document under the first element matching the parentSelector
*/
function addVideo(parentSelector, src, width, height) {
const parent = document.querySelector(parentSelector);
/*
Check that parent exists before proceeding
*/
if(parent) {
/*
Create new video element
*/
const video = document.createElement('video');
video.setAttribute('controls', true);
if(width) {
video.setAttribute('width', width);
}
if(height) {
video.setAttribute('height', height);
}
/*
Create a new source element and populate it with the src
attribute
*/
const source = document.createElement('source');
source.setAttribute('src', src);
/*
Add source element to the video we're inserting and add
the video element to the document element
*/
video.appendChild(source);
parent.appendChild(video);
}
}
// Update source of existing video
setVideoSource('#video', 'https://www.w3schools.com/html/mov_bbb.mp4')
// Add a new video to the page
addVideo('#parent', 'https://www.w3schools.com/html/mov_bbb.mp4', '100%', '150px')
<h3>Existing video dynamically updated with JavaScript</h3>
<video id="video" controls preload="metadata" style="width:100%; height:100%">
<source src="~/Content/Videos/Sample_Vid.mp4" type="video/mp4">
</video>
<h3>New video dynamically added to page with JavaScript</h3>
<div id="parent">
</div>
希望有帮助!