javascript - 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);
}
推荐阅读
- python - 模棱两可的系列的真值
- javascript - 与 Angular 的对话流实现集成未提供正确的回复
- python - 在pyqt5中单击按钮时显示熊猫数据框
- angular - 如何将动态样式应用于列,其中有数字类型值,我想根据值的范围应用颜色
- r - 使用 for 循环遍历目录
- c# - JSON 到 C# 类的无效类型对象具有不一致的数字名称
- html - 设置高度尽可能占用最小宽度的 div
- bash - 尝试通过 docker exec 获取 bash,但没有任何效果(Jaeger 容器)-> OCI 运行时 exec 失败
- jquery - 使用 ASP.NET 和 jQuery 执行 SQL Server 脚本的最佳方式?
- vue.js - Vue.js 与 CSS 网格表不兼容