Прочитать видео путь, используя JavaScript - PullRequest
0 голосов
/ 12 февраля 2019

Как прочитать путь к видео, используя 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>

1 Ответ

0 голосов
/ 12 февраля 2019

Если я правильно понимаю ваш вопрос, то вы можете:

  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>

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...