如何解决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] 进行访问,但是通常最好在访问元素之前检查数组长度。
所以,我想你可以做类似的事情
/ *,它将选择第一个视频元素,假设您的视频具有名为“ Video”的类 你也可以使用 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(tag)获取与该标签匹配的每个元素。您可以使用style.display =“ none”轻松隐藏元素。如果您要不断检查,可以使用以下代码重复上面的代码:
setInterval(function(){
},1); // repeats every millisecond
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。