在现代 Web 应用程序中,为用户提供跨会话保存进度的无缝体验至关重要。最常见的用例之一是跟踪用户观看了多少视频,以便他们可以从上次停下的地方继续播放。本教程将引导您了解如何使用 JavaScript、localStorage 和事件侦听器来实现这样的系统,同时还集成服务器端通信来存储观看时间。
**
准则概述
**
所提供的解决方案允许跟踪网页上多个视频的观看时间。它将观看进度存储在浏览器的 localStorage 中,如果用户超过上次观看时间,则使用 POST 请求更新服务器端数据库中的进度。我们的目标是提供一种通用的、可扩展的方法,以最小的努力适用于所有视频。
<video> <pre class="brush:php;toolbar:false"><video> <p>: This element embeds a video player on the page.</p> <p>The> The data-idvideo="123" is a custom attribute that holds a unique identifier for each video. This ID allows us to track and store the watch progress for individual videos.<br> <source src="path/to/video.mp4" type="video/mp4">: Specifies the path to the video file and the video format (in this case, MP4)<br> </source></p> <pre class="brush:php;toolbar:false">// Function to update the watched time function updateWatchedTime(video, videoId) { var timeInSeconds = video.currentTime; // Time watched in seconds var minutes = Math.floor(timeInSeconds / 60); // Whole part (minutes) var seconds = timeInSeconds % 60; // Remaining seconds var decimalTime = minutes + (seconds / 60); // Converts seconds into a fractional minute // Get the last recorded time for the video (saved in localStorage or a global variable) var lastRecordedTime = localStorage.getItem("lastRecordedTime_" + videoId); if (lastRecordedTime === null) { lastRecordedTime = 0; // Default value if no previous time is found } else { lastRecordedTime = parseFloat(lastRecordedTime); } // Check if the current time is greater than the last recorded time if (decimalTime > lastRecordedTime) { // If the current time is greater, save the new time var requestData = "VIDEO_ID=" + videoId + "&WATCHED_TIME=" + decimalTime.toFixed(4); console.log("Sending: " + requestData); // Shows the watched time in decimal (4 decimal places) // Send the data to the server (replace with actual URL) $.post("path/to/api", requestData, function(response) { // Handle server response if needed console.log("Server response: " + response); // After saving, update the localStorage with the new watched time localStorage.setItem("lastRecordedTime_" + videoId, decimalTime.toFixed(4)); }); } else { console.log("Watched time is less than the last recorded time. No update sent."); } } // Add an event listener for the 'timeupdate' event to all video elements document.querySelectorAll('.videoCourse').forEach(function(video) { // Get the video ID (should be uniquely assigned to each video element) var videoId = video.getAttribute('data-idvideo'); // Add the 'timeupdate' event listener video.addEventListener('timeupdate', function(event) { updateWatchedTime(video, videoId); // Pass the video and its ID directly }); });
**
守则解释
- 更新观看时间功能** 该解决方案的核心是 updateWatchedTime() 函数。该函数负责:
计算观看进度:该函数首先检索视频的当前时间(以秒为单位)并将其转换为分钟和秒。然后时间将转换为十进制格式(例如,3 分 30 秒变为 3.50)。
检查上次录制时间:使用 localStorage.getItem() 方法,我们检索视频的上次录制时间。如果尚未记录时间(即用户第一次观看视频),则默认为 0。这确保进度跟踪从零开始。
存储时间:如果当前时间大于上次记录时间,则意味着自上次更新以来用户已经观看了更多视频。该函数使用 POST 请求将更新的时间发送到服务器。数据发送成功后,localStorage 会更新为新时间。
2。处理多个视频
该脚本使用 > 向页面上的所有视频添加事件侦听器
事件监听器:每次视频时间更新时(即,当用户观看视频时),都会触发 timeupdate 事件。此事件在视频播放时持续触发,提供了跟踪进度的机会。
querySelectorAll():此方法选择页面上的所有视频元素,使脚本适用于任意数量的视频。它循环遍历每个视频,附加 timeupdate 侦听器,确保独立跟踪每个视频的观看进度。
**
这是如何工作的:分步流程
**
用户观看视频:当用户观看视频时,timeupdate 事件不断触发。
计算观看进度:脚本计算视频的观看时长(以分钟和秒为单位),然后将其转换为十进制格式。
最后记录时间:该脚本将当前观看时间与 localStorage 中保存的最后记录时间进行比较。
必要时更新:如果当前观看时间大于之前保存的时间,则将新时间发送到服务器。之后,新时间将保存在 localStorage 中。
下次访问:下次用户访问该页面时,脚本会检查 localStorage 的上次保存时间。如果可用,它会从用户离开的位置开始跟踪。
**
优点和用例
**
可扩展性:此方法适用于页面上任意数量的视频。它使用 data-idvideo 属性来唯一标识每个视频,使系统无需修改即可扩展。
持久性:使用 localStorage,可以跨会话保存用户的进度。即使页面重新加载或者用户离开并返回,他们的进度也会保留。
无缝集成:该解决方案与现有视频播放器顺利集成,使其可以轻松在已使用 HTML5
以上是使用 JavaScript 跟踪视频观看进度的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3汉化版
中文版,非常好用

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

Atom编辑器mac版下载
最流行的的开源编辑器