我有一个用于练习的示例网站,我向其中添加了一个视频,其中包含一些带有 JavaScript 的按钮。 当我在 HTML 文件中运行脚本时,它运行得很好,但如果我尝试从 .js 文件运行它,它就不起作用,按钮也不会执行任何操作。 有什么想法吗?
html:
<!DOCTYPE html>
<html>
<head>
<title>Blue Developer Directory</title>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css">
<script type="text/javascript" src="js.js"></script>
</head>
<body>
<video id="ad" width="420" height="350" controls>
<source src="video/ad.mp4" type="video/mp4">
Please update your browser
</video>
<div style="width:400px;">
<button onclick="playPause()">Play/Pause</button>
<button onclick="makeBig()">Big</button>
<button onclick="makeSmall()">Small</button>
<button onclick="makeNormal()">Normal</button>
</div>
</body>
Javascript:
var myVideo=document.getElementById(ad);
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;
}
最佳答案
一个问题:
var myVideo=document.getElementById(ad);
需要报价:
var myVideo=document.getElementById('ad');
我还将删除内联事件处理程序并设置函数调用,如下所示:
<button id="play">Play/Pause</button>
还有 JS:
var play=document.getElementById('play');
play.onclick = function() {
playPause();
}
关于JavaScript 函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19824918/