Javascript-视频播放/暂停按钮

Javascript - Play/ Pause button for video

本文关键字:暂停 按钮 播放 视频 Javascript-      更新时间:2023-09-26

对于我的大学工作,我必须制作视频控件,我试图实现一个播放/暂停按钮,但它不起作用。这是我的代码:

HTML:

<script src="Scripts/VideoScript.js"></script>
<section id="Example_Video_Container">
    <video width = 576 height = 432 id = "Example_Video">  
        <source src="Videos/Example_Video.mp4">
        <source src="Videos/Example_Video.webm">
    </video>
    <div id="Example_Video_Controls">
        <button type="button" id="Play_Pause" >Play</button>
    </div>
</section>

JavaScript:

window.addEventListener (“DOMContentLoaded”,handleWindowLoad) 
function handleWindowLoad ()
{
    var Video = document.getElementById ( "Example_Video" );
    var PlayButton = document.getElementById ( "Play_Pause" );
    var MuteButton = document.getElementById ( "Mute_Unmute" );
    var Slider = document.getElementById ( "Slider" );
    PlayButton.addEventListener ( "click", Play_Pause_Video ) ;
    function Play_Pause_Video ()
    {
        if (Video.paused === true)
        {
            Video.play();
            PlayButton.innerHTML = "Pause";
        }
        else
        {
            Video.pause();
            PlayButton.innerHTML = "Play";
        }
    }
}

我也检查了我的文件路径,它们应该都是好的。

看看这个小提琴

您的代码运行良好。您在浏览器控制台中得到了一个Uncaught SyntaxError: Unexpected token ILLEGAL,这是由于

注意window.addEventListener (“DOMContentLoaded”,handleWindowLoad)中的。javascript识别的并不是真正的"。更换为"。因此JS代码将类似

window.addEventListener ("DOMContentLoaded",handleWindowLoad);
function handleWindowLoad ()
{
    var Video = document.getElementById ( "Example_Video" );
    var PlayButton = document.getElementById ( "Play_Pause" );
    var MuteButton = document.getElementById ( "Mute_Unmute" );
    var Slider = document.getElementById ( "Slider" );
    PlayButton.addEventListener ( "click", Play_Pause_Video ) ;
    function Play_Pause_Video ()
    {
        if (Video.paused === true)
        {
            Video.play();
            PlayButton.innerHTML = "Pause";
        }
        else
        {
            Video.pause();
            PlayButton.innerHTML = "Play";
        }
    }
}

检查控制台是否存在错误。我注意到一个-

Javascript Error: 'missing ) after argument list"

要解决此问题,请替换window.addEventListener()

带有:

document.addEventListener("DOMContentLoaded", function(event) {
    handleWindowLoad();
});

HTML5包含视频控件的内置属性。

查看此页面以获取帮助:http://www.w3schools.com/tags/att_video_controls.asp

代码在技术上是正确的,应该可以正常工作,但有一个小错误。

21:17:37.737 SyntaxError: illegal character1 VideoScript.js:1:26

在VideoScript.js中,第26个字符在第1行是非法的。

window.addEventListener (“DOMContentLoaded”,handleWindowLoad) 

删除这个奇怪的双引号("),并将其替换为普通引号("),它将正常工作:)

window.addEventListener ("DOMContentLoaded",handleWindowLoad)

这就是为什么您应该使用调试工具。

这里有一些提示可以找出这样的小错误:

  • 如果您使用FireFox,请单击Ctrl+Shift+J并打开浏览器控制台窗口
  • 刷新加载有问题的HTML文件的选项卡
  • 检查浏览器控制台,你会看到是否有任何错误
  • 复制错误并用谷歌搜索