暂停按钮不工作在背景视频

时间:2016-11-10 15:04:46

标签: javascript html5-video

我试图创建一个漂亮的背景视频,顶部有一些文本以及一个可用于暂停和取消暂停视频的按钮,视频工作正常并循环,但我无法暂停视频。

<html>

<head>
<script src="js/script.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="css/custom.css">
</head>

<body>
<video poster="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/polina.jpg" id="bgvid" playsinline autoplay muted loop>
<source src="dudleyByDrone.mp4" type="video/mp4">
</video>
<div id="polina">
    <h1>dudley</h1>
    <p>Directed by joe bloggs
        <p><a href="">original article</a>
          <p>blah blah</p>
            <button>Pause</button>
</div>
</body>

</html>

js(我从here得到了这个代码,虽然它说“//只有”如果“循环”被删除“我已经尝试删除”循环“并且它仍然没有暂停:

var vid = document.getElementById("bgvid");
var pauseButton = document.querySelector("#polina button");

function vidFade() {
    vid.classList.add("stopfade"); 
}

vid.addEventListener('ended', function()
{
// only functional if "loop" is removed 
   vid.pause();
// to capture IE10
   vidFade();
}); 
pauseButton.addEventListener("click", function() {
   vid.classList.toggle("stopfade");
 if (vid.paused) {
   vid.play();
   pauseButton.innerHTML = "Pause";
} else {
   vid.pause();
   pauseButton.innerHTML = "Paused";
  }
})

2 个答案:

答案 0 :(得分:1)

以下代码可让您暂停视频

$(function() {
    $('#polina button').on("click", function() {
        $('video')[0].pause();
    });
});

编辑:将pause();更改为play();将完全符合您的预期。

答案 1 :(得分:1)

您需要更具体地引用该按钮。

 var playPause = document.querySelector("#playPause");

整个源playButton的更改已更改为playPause,这不是问题,只是偏好。间接选择器可能适用于document.querySelector(),也可能不适用,因为它更容易接受简单的选择器(从经验来看,不确定是否记录在案。)

var vid = document.getElementById("bgvid");
var playPause = document.querySelector("#playPause");

function vidFade() {
  vid.classList.add("stopfade");
}

vid.addEventListener('ended', function() {
  // only functional if "loop" is removed 
  vid.pause();
  // to capture IE10
  vidFade();
});
playPause.addEventListener("click", function() {

  if (vid.paused) {
    vid.play();
    playPause.innerHTML = "Pause";
  } else {
    vid.pause();
    playPause.innerHTML = "Paused";
  }
})
<html>

<head>
  <script src="js/script.js" type="text/javascript" charset="utf-8"></script>
  <link rel="stylesheet" href="css/custom.css">
</head>

<body>
  <video poster="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/polina.jpg" id="bgvid" playsinline autoplay muted loop>
    <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
  </video>
  <div id="polina">
    <h1>dudley</h1>
    <p>Directed by joe bloggs
      <p><a href="">original article</a>
        <p>blah blah</p>
        <button id="playPause">Play/Pause</button>
  </div>
</body>

</html>