Обновление <video>время на основещелчок - PullRequest
0 голосов
/ 07 мая 2019

Я использую приведенный ниже код, чтобы попытаться обновить атрибут currentTime HTML5 video с указанным временем в зависимости от того, где пользователь нажимает seekBar. Однако вместо этого я просто добавляю текущее время видео, а не выбранное кликом seekBar. У меня неправильные вычисления в переменной time? Любая помощь будет высоко ценится.

<video id="video" src="videourl.com" preload></video>
<input id="seek-bar" type="range" min="0" max="100" value="0" step="0.05">


// Vars 
var video = document.getElementById('video');
var seekBar = document.getElementById('seek-bar');

// Create clickable seek bar and update video position
seekBar.on('input change', function() {

    // Calculate the new time
    var time = video[0].duration * (seekBar.value / 100);

    // Update the video time
    video[0].currentTime = time;
});

1 Ответ

0 голосов
/ 08 мая 2019

Есть несколько ошибок в коде OP (согласно комментариям).Похоже, что это был jQuery и была попытка конвертировать его в JavaScript?Если это так, то:

....on('input change',...

.on() - это метод jQuery, который не существует, используйте свойство on-event или .addEventListener()

Разыменование с помощью [0]или .get(0) необходим для ссылки на простой объект JavaScript из объекта jQuery, поэтому он не нужен.

Подробности прокомментированы в демонстрационной версии

// Reference the <form>
const uix = document.forms.uix;
// Register the <form> to input event
uix.oninput = userInterface;

/*
--Callback pases the Event Object
- Reference the <video>
- Reference the clicked, inputed, changed, etc element
- Collect all <form> controls (<input><output><fieldset>)

- If the <input> matches by it's id #seek...
- Calculate the relative values of the #seek and #vid
- #vid Pause() Set currentTime to the value of #seek
- update output#view to value of #seek
*/
function userInterface(e) {
  const vid = document.getElementById('vid');
  const tgt = e.target;
  const view = this.elements.view;

  if (tgt.matches('#seek')) {
    const time = vid.duration * (tgt.valueAsNumber * 0.01);
    vid.pause();
    vid.currentTime = time;
    vid.play();
    view.value = tgt.value;
  }
  return false;
}
     :root {
      font: 700 5vh/1 Consolas
    }
    
    fieldset {
      width: fit-content;
      margin: 2vh auto;
      padding: 1px
    }
    
    video {
      display: block;
      width: 50vw;
      height: auto;
      ,
      margin-bottom: 0
    }
    
    input,
    output {
      font: inherit;
      display: inline-block;
      height: 10vh;
      line-height: 10vh;
      vertical-align: middle;
    }
    
    output {
      width: 25%
    }
    
    input {
      width: 60%;
      margin: 0 0 -25px 25px;
    }
<!DOCTYPE html>
<html>

<head>
  <style>
,1--CSS goes here-->
  </style>
</head>

<body>

  <form id='uix'>
    <fieldset>

      <video id='vid' src="https://storage04.dropshots.com/photos6000/photos/1381926/20170326/005610.mp4" preload></video>

      <input id="seek" type="range" min="0" max="100" value="0" step="0.05">
      <output id='view' for='seek'></output>

    </fieldset>
  </form>
  <script>
    <!-- JavaScript goes here-->
  </script>
</body>

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