Angular 12视频时间范围保存跳转异常问题求助
问题排查与修复
问题描述
基于Angular 12开发视频时间范围保存与检索功能,其余功能正常,但点击已保存的时间范围时跳转不准确:点击起始时间后会直接跳转到视频末尾。
错误原因分析
- 时间单位混淆:保存时间范围时,将进度条的**百分比值(0-100)**直接存入
commentsArr,而非转换为视频实际秒数;跳转时又错误地将百分比值当作秒数计算,导致数值远大于视频时长,触发Math.min(middleTime, videoElement.duration)后直接跳转到末尾。 - 全局变量滥用:跳转方法
goToTimeTimeRange依赖全局的savedStartTime和savedEndTime,而非当前点击的评论对应的时间范围,导致点击旧评论时使用的是最新保存的范围数据。
修复步骤
1. 修正时间范围保存逻辑
修改onSaveTimeRange方法,将进度条百分比转换为视频实际秒数后再存入数组:
onSaveTimeRange() { const videoElement = this.videoPlayer.nativeElement; const duration = videoElement.duration; if (this.selectionStart !== null && this.selectionEnd !== null) { // 将百分比转换为视频实际秒数 const startSeconds = (this.selectionStart / 100) * duration; const endSeconds = (this.selectionEnd / 100) * duration; this.savedStartTime = startSeconds; this.savedEndTime = endSeconds; const comment = { start: startSeconds, end: endSeconds, text: this.newComment, user: 'shirish' }; this.commentsArr.push(comment); this.selectionStart = null; this.selectionEnd = null; this.newComment = ''; // 清空评论输入框 } }
2. 修正跳转逻辑
修改goToTimeTimeRange方法,使用当前点击的评论对应的时间范围,而非全局变量:
// 接收当前点击的评论对象 goToTimeTimeRange(comment: { start: number, end: number }) { const videoElement = this.videoPlayer.nativeElement; // 计算时间范围的中间点 const middleTime = (comment.start + comment.end) / 2; // 确保时间在视频有效时长范围内 const currentTime = Math.max(Math.min(middleTime, videoElement.duration), 0); videoElement.currentTime = currentTime; videoElement.pause(); }
3. 更新HTML调用
修改评论列表的点击事件,传入整个评论对象,并优化时间显示格式:
<div class="comments-container"> <h2>时间范围评论</h2> <div class="comment" *ngFor="let comment of commentsArr" (click)="goToTimeTimeRange(comment)"> <p>{{ comment.user }} - {{ comment.text }} ({{ formatDuration(comment.start) }} - {{ formatDuration(comment.end) }})</p> </div> </div>
额外优化建议
- 移除代码中冗余的
debugger语句,避免影响生产环境性能。 - 统一时间显示逻辑,全部使用
formatDuration方法格式化时间,提升用户体验。
内容的提问来源于stack exchange,提问作者sTg
相关产品推荐
相关产品推荐

