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))
} 
});

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

你能分享你的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);
}

document.getElementsByClassName('class_name')返回一个NodeList,而不仅仅是一个节点。

因此,如果只有一个视频元素具有video类名,那么您应该将nextButton.classList.add('d-none');更改为nextButton[0].classList.add('d-none');

或者,如果您有多个video类命名元素,那么您应该考虑使用一个循环,并向其中每个元素添加一个ended事件侦听器。

还修复了您的setTimeout功能,

setTimeout(() => {
nextButton.classList.remove('d-none')
}, duration);

if(document.getElementsByTagName("video").length > 0){
document.getElementById("idOfNextButton").style.display = "none";
}

document.getElementsByTagName(标记(获取与该标记匹配的每个元素。使用style.display="可以很容易地隐藏元素;没有";。如果你想经常检查这个,你可以使用以下代码重复上面的代码:

setInterval(function(){
}, 1); // repeats every millisecond

相关内容

最新更新