简体   繁体   English

如何单独暂停/播放 html5 视频

[英]How to pause/play html5 videos individually

I have a page with a list of videos.我有一个包含视频列表的页面。 I would like to add a pause/play button to each of them, so that they can be controlled individually.我想为它们中的每一个添加一个暂停/播放按钮,以便可以单独控制它们。

I can't seem to make it work, though.不过,我似乎无法让它工作。 Each video have this markup:每个视频都有这个标记:

<div class="media-container">
  <button class="pause-play" type="button">Pause/play</button>
  <div class="video">
    <video playsinline loop muted autoplay>
      <source src="https://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
    </video>
  </div>
</div>

Here's what I have tried:这是我尝试过的:

onload = e => {
  const containers = Array.prototype.slice.apply(document.querySelectorAll('.media-container'));
  containers.forEach(container => {
    const video = container.querySelector('video');
    const playButton = container.querySelector('.pause-play');
    playButton.addEventListener('click', e => {
      //Pause this individual video...? video.pause();
    })
  })
}

The error I get is: Uncaught TypeError: Cannot read property 'addEventListener' of null我得到的错误是: Uncaught TypeError: Cannot read property 'addEventListener' of null

JsFiddle here JsFiddle在这里

jQuery is an option as well... jQuery 也是一个选项...

As you say I would like to add , I guess that .pause-play button is not in the page (or maybe it's in the page but not inside .media-container ), so rather than grabbing a reference to an existing element:正如您所说,我想添加,我猜.pause-play按钮不在页面中(或者它在页面中但不在.media-container内部),而不是获取对现有元素的引用:

const playButton = container.querySelector('.pause-play');

You should be creating one:您应该创建一个:

const playButton = document.createElement('BUTTON');
playButton.className = 'pause-play';
playButton.addEventListener('click', () => { ... });
container.appendChild(playButton);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM