我想做一个快速的实验,是否可以制作自己的简单视频播放器。到目前为止,这是我的HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<div style="text-align:center">
<button onclick="playPause()">Play/Pause</button>
<button onclick="makeBig()">Big</button>
<button onclick="makeSmall()">Small</button>
<button onclick="makeNormal()">Normal</button>
<br><br>
<video id="video1" width="420">
<source src="https://www.sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
</div>
<script>
var myVideo = document.getElementById("video1");
function playPause() {
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
function makeBig() {
myVideo.width = 560;
}
function makeSmall() {
myVideo.width = 320;
}
function makeNormal() {
myVideo.width = 420;
}
</script>
</body>
</html>
如您所见,它可以完美运行。星期四,如果我将脚本添加到新文件中,则结果如下。
alert("file included."); // check if file has been included correctly
var myVideo = document.getElementById("video1");
function playPause() {
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
function makeBig() {
myVideo.width = 560;
}
function makeSmall() {
myVideo.width = 320;
}
function makeNormal() {
myVideo.width = 420;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<div style="text-align:center">
<button onclick="playPause()">Play/Pause</button>
<button onclick="makeBig()">Big</button>
<button onclick="makeSmall()">Small</button>
<button onclick="makeNormal()">Normal</button>
<br><br>
<video id="video1" width="420">
<source src="https://www.sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
</div>
</body>
</html>
好的,因此由于某些原因它仍然可以工作,但是如果将代码复制到“ index.html”和“ main.js”中,则会出现以下错误:
Uncaught TypeError: Cannot read property 'paused' of null
at playPause (main.js:6)
at HTMLButtonElement.onclick ((index):10)
当javascript代码包含在html中时,不会发生该错误。 这是为什么?我用的是铬。
谢谢!
答案 0 :(得分:1)
由于DOM尚未完全加载,因此无法访问ID为id photo_type likes comments hash-tags
1 nature 2 1 [#nature, #shooting, #photography]
2 art 4 5 [#shooting, #photography]
3 art 1 3 [#art, #shooting]
4 fashion 3 0 [#beauty, #photography]
5 fashion 2 0 [#shooting, #photography]
的元素。考虑将video1
元素移到script
的底部或使用事件DOMContentLoaded
。
答案 1 :(得分:1)
将脚本移到正文末尾。您试图在元素存在之前获取它。
body
var myVideo = document.getElementById("video1");
答案 2 :(得分:1)
向您的JS文件添加一个onload侦听器:
window.onload = function() {
// All your code
};
或者,将<script>
标记移到文件的末尾,紧接在结束</body>
标记之前:
<script src="main.js" type="text/javascript"></script>
</body>
答案 3 :(得分:1)
如果要包含其他文件中的功能,则需要加载视频。
myVideo.load()
应该可以解决。