我正在尝试使用两个单独的按钮开始和停止两个视频。我只是复制了代码并重命名了变量,但一段代码可以工作,而另一段则不能。我收到错误“TypeError:video2.pause 不是 HTMLButtonElement.c 中的函数”。视频和按钮都分别放置在模态中。为什么我会收到这个奇怪的错误,尤其是当完全相同的代码工作时?
Javascript:
var video = document.getElementById("video.mp4");
var playButton = document.getElementById("play-pause");
var video2 = document.getElementById("video2.mp4");
var play = document.getElementById("play-pause2");
playButton.addEventListener("click", function a () {
if (video.paused == true) {
video.play();
playButton.innerHTML = "Pause";
} else {
video.pause();
playButton.innerHTML = "Play";
}
});
play.addEventListener("click", function c () {
if (video2.paused == true) {
video2.play();
play.innerHTML = "Pause";
} else {
video2.pause();
play.innerHTML = "Play";
}
});
HTML:
<video width="900px" height="600px" id="Digital_Poster.mp4" />
<source src="assets/video.mp4" type="video/mp4" id="video.mp4"/>
Sorry, this browser does not support the 'video' tag.
</video>
<div id="video-controls">
<button type="button" id="play-pause">Play</button>
</div>
<video width="900px" height="600px">
<source src="assets/video2.mp4" type="video/mp4" id="video2.mp4"/>
Sorry, this browser does not support the 'video' tag.
</video>
<div id="video-controls">
<button type="button" id="play-pause2">Play</button>
</div>
最佳答案
您应该调用.pause
关于<video>
元素,但是 id
设置在 <source>
那些。将其移至<video>
标签应该让它工作:
<video width="900px" height="600px" id="video.mp4">
<source src="assets/video.mp4" type="video/mp4" />
Sorry, this browser does not support the 'video' tag.
</video>
<div id="video-controls">
<button type="button" id="play-pause">Play</button>
</div>
<video width="900px" height="600px" id="video2.mp4">
<source src="assets/video2.mp4" type="video/mp4" />
Sorry, this browser does not support the 'video' tag.
</video>
<div id="video-controls">
<button type="button" id="play-pause2">Play</button>
</div>
顺便说一下,我已经更正了 />
至>
在第一行。另外,声明两个 ID 设置为 video-controls
的元素非法,请考虑使用 HTML classes (感谢@zer00ne 的指出)。
关于JavaScript 'x is not a function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41916207/