如何修复mouseover触发视频播放时play()被pause()中断的DOMException错误
修复视频播放时的
Uncaught (in promise) DOMException错误 错误原因
video.play()会返回一个Promise,当鼠标快速在元素间移入移出时,某个视频的play请求还处于pending状态就被pause()操作打断,导致Promise拒绝且未被捕获,从而触发控制台报错。
修复方案
核心是给play()的Promise添加错误捕获,同时可以优化代码减少重复逻辑,以下是两种处理方式:
方式一:直接修改原代码,添加错误捕获
milano.onmouseover = VideoS; milano.onmouseout = VideoF; parigi.onmouseover = VideoS; parigi.onmouseout = VideoF; ny.onmouseover = VideoS; ny.onmouseout = VideoF; londra.onmouseover = VideoS; londra.onmouseout = VideoF; function VideoS() { switch (this.id) { case 'milano': video3.play().catch(err => { // 捕获play被pause打断的特定错误,避免控制台报错 if (err instanceof DOMException && err.message.includes('interrupted by a call to pause()')) { return; } console.error('视频播放异常:', err); }); break; case 'parigi': video4.play().catch(err => { if (err instanceof DOMException && err.message.includes('interrupted by a call to pause()')) { return; } console.error('视频播放异常:', err); }); break; case 'ny': video5.play().catch(err => { if (err instanceof DOMException && err.message.includes('interrupted by a call to pause()')) { return; } console.error('视频播放异常:', err); }); break; case 'londra': video6.play().catch(err => { if (err instanceof DOMException && err.message.includes('interrupted by a call to pause()')) { return; } console.error('视频播放异常:', err); }); } } function VideoF() { switch (this.id) { case 'milano': video3.pause(); video3.currentTime = 0; break; case 'parigi': video4.pause(); video4.currentTime = 0; break; case 'ny': video5.pause(); video5.currentTime = 0; break; case 'londra': video6.pause(); video6.currentTime = 0; } }
方式二:优化代码结构,减少重复逻辑
通过建立ID与视频元素的映射表,批量绑定事件,让代码更简洁易维护:
// 建立元素ID对应视频元素的映射 const videoMap = { 'milano': video3, 'parigi': video4, 'ny': video5, 'londra': video6 }; // 批量为元素绑定鼠标事件 ['milano', 'parigi', 'ny', 'londra'].forEach(id => { const element = document.getElementById(id); element.onmouseover = VideoS; element.onmouseout = VideoF; }); function VideoS() { const targetVideo = videoMap[this.id]; if (targetVideo) { targetVideo.play().catch(err => { // 仅忽略play被pause打断的错误,其他异常正常输出日志 if (!(err instanceof DOMException && err.message.includes('interrupted by a call to pause()'))) { console.error('视频播放出错:', err); } }); } } function VideoF() { const targetVideo = videoMap[this.id]; if (targetVideo) { targetVideo.pause(); targetVideo.currentTime = 0; } }
说明
两种方案都保留了你要求的onmouseover/onmouseout交互逻辑,功能完全不变,只是通过捕获play()返回Promise的拒绝状态,解决了控制台报错问题。优化后的代码结构更适合后续扩展,比如新增视频元素时只需修改映射表和绑定数组即可。
内容的提问来源于stack exchange,提问作者gabri987
相关产品推荐
相关产品推荐

