点击视频灯箱外围遮罩层边缘无法关闭的问题如何修复
问题根因
你遇到的点击边缘无法关闭的问题来自三个核心错误:
#motionLight采用absolute定位且设置了10vw的内边距,这部分透明内边距的层级比遮罩层#motionFade高(z-index 1002 > 1001),点击视频边缘时实际命中的是#motionLight的内边距区域,不会触发遮罩层的关闭事件#motionLight是绝对定位,会跟随文档流滚动,打开弹窗时你主动调用了window.scrollTo(0,150)滚动页面,导致弹窗位置上移,原本被内边距盖住的遮罩层才暴露出来可以点击- JS代码中获取视频元素的ID写错了,HTML里弹窗内的视频ID是
motionShowreel,不是motionGraphic,会引发JS报错影响功能执行
修复方案
1. 修改CSS部分
调整#motionLight的定位逻辑,改为固定定位居中,去掉多余的内边距避免遮挡遮罩层:
#motionLight { display: none; position: fixed; /* 基于视口居中,不受页面滚动影响 */ top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 1002; cursor: pointer; /* 移除撑开容器的内边距 */ padding: 0; }
2. 修改JS部分
修正ID匹配错误,删除不必要的页面滚动代码:
window.document.onkeydown = function(e) { if (!e) { e = event; } if (e.keyCode == 27) { motionLightbox_close(); } } function motionLightbox_open() { // 修正视频ID匹配 var lightBoxVideo = document.getElementById("motionShowreel"); // 移除强制页面滚动的逻辑 // window.scrollTo(0,150); document.getElementById('motionLight').style.display = 'block'; document.getElementById('motionFade').style.display = 'block'; // 如需打开后自动播放可改为lightBoxVideo.play() lightBoxVideo.pause(); } function motionLightbox_close() { var lightBoxVideo = document.getElementById("motionShowreel"); document.getElementById('motionLight').style.display = 'none'; document.getElementById('motionFade').style.display = 'none'; lightBoxVideo.pause(); // 可选:关闭时重置播放进度 // lightBoxVideo.currentTime = 0; }
3. 可选优化
给#motionLight也绑定点击关闭逻辑,避免偶尔点击到弹窗容器空白区域无法关闭的问题:
document.getElementById('motionLight').addEventListener('click', function(e) { // 仅点击视频以外的区域时触发关闭 if (e.target.tagName !== 'VIDEO') { motionLightbox_close(); } })
内容的提问来源于stack exchange,提问作者Di Jia
相关产品推荐
相关产品推荐

