其工作方式是访问视频对象的属性。这意味着我们像数组一样使用视频。如果视频暂停,我们找到播放方法,否则我们找到暂停方法。我们不是在创建新方法,我们只是在寻找对象上已经存在的方法。
function togglePlay() {
if(video.paused) {
video.play() // could also be written as video["play"]()
} else {
video.pause() // could also be written as video["pause"]()
}
}
要使togglePlay方法像您编写的那样工作,您必须将togglePlay函数中的最后一行更改为。
视频[方法]到视频[方法]();
const video = document.getElementById("video");
function togglePlay() {
const method = video.paused ? 'play' : 'pause';
video[method]();
}
<!DOCTYPE html>
<html>
<body>
<video id="video" width="320" height="240" controls>
<source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<button onclick="togglePlay()">toggle play</button>
</body>
</html>