javascript - 使用 javascript 读取视频路径
问题描述
如何使用 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>
解决方案
如果我正确理解您的问题,那么您可以:
实现
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>
希望有帮助!
推荐阅读
- python - Python Pandas:查找两个数据帧之间多列的最接近匹配
- javascript - 如何从 instagram 应用内浏览器页面链接打开默认浏览器?
- angular - 如果无法导入 TranslocoService,如何翻译 const 文件?
- c# - Tab 而不是 Enter
- python - Pyspark - 使用新的列名从长到宽
- kubernetes - 在部署中重用 PV
- c++ - 使用 MariaDB c++ 连接器和正则表达式时发生 Segfault
- google-cloud-platform - 如何使用 terraform 在 GCP VM 实例上启用 bigtable api(读取)
- java - 如何为 SFTP 服务器正确指定目录路径?
- python-2.7 - 如何利用管理程序的 python2.7 库及其对作为 lxc 容器运行的 VM 的依赖关系