首页 > 解决方案 > 使用 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>

标签: javascriptasp.net-mvc

解决方案


如果我正确理解您的问题,那么您可以:

  1. 实现setVideoSource()如下所示的功能,它允许您设置/更改页面中已存在的视频元素的来源,或者,

  2. 实现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>

希望有帮助!


推荐阅读