首页 > 解决方案 > Javascript函数检查页面上是否有视频,然后在视频持续时间内隐藏下一个按钮

问题描述

我正在尝试构建一个函数来检查 html 页面上的视频,如果存在,则在视频持续时间内隐藏页面上的下一个按钮。到目前为止,我的代码如下所示:

<script type="text/javascript">

$(document).onload(function () {
    //grab video in variable
    var video = document.getElementsByClassName("Video");
    //if video exists, hide the next button, get duration
    if (typeof (video) != 'undefined' && video != null) {
        //grab the next button by 'next' class
        var nextButton = document.getElementsByClassName('next');
        //hide next by adding bootstrap 'd-none' class
        nextButton.classList.add('d-none');
        //grab duration on video to set timer
        var duration = video.duration;
        //set a timer for the duration of the video
        setTimeout(nextButton.classList.remove('d-none', duration))
    } 
    });

我不确定为什么我的功能不起作用。任何帮助都会很棒,谢谢。

标签: javascripthtmlasp.net-mvc

解决方案


你能分享你的 HTML 和你正在使用的 jquery 版本吗?

到目前为止,这是我在上面的代码中注意到的一些事情

我建议您在正在开发的页面中尝试使用 chrome 控制台中的选择器。

从此开始。

var video = document.getElementsByClassName("Video");

我建议检查MDN以获取有关getElementsByClassName的文档

它返回与您的选择器匹配的元素数组,而不是单个元素(假设每个视频元素都有一个名为Video的类)

因此,要访问元素,它应该以video[0]的形式访问,但在访问元素之前检查数组长度通常是个好主意。

所以,我想你可以做类似的事情

/*这将选择第一个视频元素,假设您的视频有一个名为“视频”的类,您也可以使用 var video = document.getElementsByTagName("video")[0]; */

var video = document.getElementsByClassName("Video")[0];
//check if the element exists
if (video) {
    //select the "Next" button, assumuing it has a class named 'next'
    var nextButton = document.getElementsByClassName('next')[0];
    //hide next by adding bootstrap 'd-none' class
    nextButton.classList.add('d-none');

    //start playing the video
    video.play();
    /*grab duration on video to set timer
    note the *1000, 
    since setTimeout takes time in milliseconds, we need to multiply by 1000 to convert to seconds
    */var duration = video.duration * 1000;
    //set a timer for the duration of the video

    /**
     * The syntax here was not correct.
     * setTimeout takes a function as first parameter, the duration as second parameter.
     */
    setTimeout(() => {
        //hide the timer on video duration over
        nextButton.classList.remove('d-none')
    }, duration);

}

推荐阅读