javascript - 如何将视频的当前时间作为事件来运行&
问题描述
每个人!我是 JavaScript 新手。假设我有一个视频,并且我希望当它播放一定秒数(比如 5 秒)时,my_function 将执行(例如,应该在控制台中显示单词“五”)。出于某种原因,下面的代码正确显示了当前视频的秒数,但未在控制台中显示该单词。
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text</title>
</head>
<body>
<div class="container">
<video width="400" controls id="video">
<source src="video/video.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
<span class="timelapse" id='current'> </span>
</div>
<button id='getTime'>getTime</button>
</body>
<script src="js/script.js"></script>
</html>
脚本.js:
var aud = document.getElementById('video');
aud.ontimeupdate = function(){myFunction()};
function myFunction(){
document.getElementById('current').innerHTML = aud.currentTime;
if (aud.currentTime == 5.0){
console.log('Hello!');
}
};
谢谢!
解决方案
我真蠢!我将当前视频时间与特定数字(在 5.0 的示例中)进行了比较。但是,“捕获”脚本的视频的时间可能与 5.0 不同:5.1、5.121、5.132 ......并且不是整数。因此,代码不起作用。为了在控制台中显示,您需要使用:aud.currentTime > 5。所以,正确的代码是:
var aud = document.getElementById('video');
aud.ontimeupdate = function(){myFunction()};
function myFunction(){
console.log();
if(aud.currentTime > 5.0){
console.log('Five')
}
};
但现在我有另一个问题。如何让 myFunction() 只执行一次?我尝试使用这个表达式:(aud.currentTime > 5.0) & (aud.currentTime < 5.3),但不能保证。
答案就在这里。
推荐阅读
- python - 从 DateTime Pandas 系列中提取小时数
- c# - C# WPF 线程:如何在事件函数中停止新创建的线程(单击按钮)。不影响主线程
- java - 在 weka jython 中处理数据属性
- sql-delete - SQL“DELETE FROM ...”不起作用,因为弹性池已满
- flutter - 有没有办法序列化 json 响应(来自 .net API)以将列表中的 $ref 对象替换为 dart 中的完整对象?
- javascript - 如何将搜索栏添加到画布外菜单?
- c# - 用于 MacBook 的 WPF C#
- ios - 在集成“iBeacon + BLE 外设扫描 iOS 后台模式”功能方面需要帮助
- visual-studio-code - Monaco 编辑器自定义令牌提供者行为
- php - 使用 PHP 合并两个透明图像