如果我能够制作自己的简单视频播放器,我想做一个快速实验。到目前为止,这是我的 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)
当 html 中包含 javascript 代码时,不会发生该错误。 这是为什么?我正在使用 Chrome 。
谢谢!
最佳答案
ID 为 video1
的元素无法访问,因为 DOM 尚未完全加载。考虑将 script
元素移动到 body
的底部或使用事件 DOMContentLoaded
.
关于javascript - 当从另一个文件中包含时,函数停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56712075/