无法阅读属性'暂停'在play_pause中为null

时间:2018-01-09 22:39:40

标签: javascript jquery html video

大家好我想制作一个自定义视频播放器。

我尝试按下按钮暂停或播放视频,但无法执行此操作。

Html代码:index.html

<html>
<head>
  <script type="text/javascript" src="../js/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src="../js/player.js"></script>
  <link rel="stylesheet" href="../css/style.css" />
  <title></title>
</head>
<body>
  <video id="main_video" src="../media/4k.mp4" controls autoplay></video>
  <p>
  <button onclick="play_pause()" type="button">PLAY/PAUSE</button>
</body>
</html>

Javascript代码:player.js

var video_screen = document.getElementById('main_video');
var play_pause_status = "play";

function play_pause()
{
  if (play_pause_status == "pause")
  {
    video_screen.play();
    play_pause_status = "play";
  }
  else
  {
    video_screen.pause();
    play_pause_status = "pause";
  }
}

当我点击按钮时,显示错误:

Uncaught TypeError: Cannot read property 'pause' of null at play_pause

我想将我的Javascript代码保存到单独的文件中。

我无法理解错误,请帮忙。

2 个答案:

答案 0 :(得分:0)

使用$(document).ready,并将代码包装在其中。在文档准备好之前调用代码。或者,您可以在函数本身中获取元素,如下面的代码段所示。

&#13;
&#13;
var play_pause_status = "play";

function play_pause() {
  var video_screen = document.getElementById('main_video');
  if (play_pause_status == "pause") {
    video_screen.play();
    play_pause_status = "play";
  } else {
    video_screen.pause();
    play_pause_status = "pause";
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="main_video" src="https://www.w3schools.com/html/mov_bbb.mp4" controls autoplay></video>
<p>
  <button onclick="play_pause()" type="button">PLAY/PAUSE</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

确保在查询之前加载DOM。您提到的错误是因为video_screen.pause()。运行脚本时(在完全加载DOM之前)video_screen元素为空,这可能是错误的原因。

$(document).ready(function() {
  var video_screen = document.getElementById('main_video');
  var play_pause_status = "play";

  function play_pause()
  {
    if (play_pause_status == "pause")
    {
      video_screen.play();
      play_pause_status = "play";
    }
    else
    {
      video_screen.pause();
      play_pause_status = "pause";
    }
  }
});