我想在点击视频时播放/暂停 我的代码在这里,
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="javascript">
$(document).ready(function () {
var myVideo = document.getElementById("video1");
function playPause()
{
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
//your code here
});
</script>
</head>
<body>
<video id="video1" onClick="playPause();" width="320" height="240" >
<source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
</video>
</body>
</html>
我在哪里卡住?它显示错误如
ReferenceError:未定义playPause
答案 0 :(得分:1)
您有几个问题:
playPause
仅在加载页面后定义,但您之前尝试绑定它。您可以删除$(document).ready()
以定义之前绑定的功能。
document.getElementById("video")
返回undefined
(除非是您帖子中的拼写错误),因为您的<video>
元素已标识为video1
这是一个有效的代码:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="javascript">
function playPause() {
var myVideo = $("#video1"); // or document.getElementById("video1");
if (myVideo.paused) {
myVideo.play();
} else {
myVideo.pause();
}
// Your code here
}
</script>
</head>
<body>
<video id="video1" onClick="playPause();" width="320" height="240" autoplay="on">
<source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
</video>
</body>
</html>
答案 1 :(得分:0)
你的函数playPause()在这里被定义为一个匿名函数。
function () {
var myVideo = document.getElementById("video");
function playPause()
{
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
//your code here
}
这意味着playPause()的范围只是这个匿名函数。这意味着你无法从任何地方打电话。
您应该在尝试调用它之前定义它。像那样:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="javascript">
function playPause(myVideo)
{
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
$(document).ready(function () {
var myVideo = document.getElementById("video");
playPause(video);
});
</script>
</head>
<body>
<video id="video1" onClick="playPause(document.getElementById("video"));" width="320" height="240" autoplay="on">
<source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
</video>
</body>
</html>
答案 2 :(得分:0)
代码中有几个问题。主要是视频的ID与您正在使用的视频不同。试试这个片段。
var myVideo = document.getElementById("video1");
function playPause()
{
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
//your code here
&#13;
<video id="video1" onClick="playPause();" width="320" height="240" autoplay="on">
<source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
</video>
&#13;