原生JS实现YouTube弹窗失效:代码问题排查与解决
问题解决:点击按钮无反应的视频弹窗修复
你的代码存在两个核心问题导致点击按钮后无任何反应,以下是针对性修复方案:
1. CSS选择器拼写错误+写法错误
你在CSS里写了.vide-container .show,这里有两处错误:
- 拼写失误:
vide-container少了字母o,正确应为video-container - 选择器逻辑错误:
.video-container .show是查找容器内部的show元素,而我们需要的是自身带有show类的视频容器,正确写法是.video-container.show
修改后的CSS片段:
/* 替换原错误选择器 */ .video-container.show { pointer-events: all; opacity: 1; } .video-container.show .video { transform: scale(1); }
2. 阻止a标签的默认跳转行为
你的按钮是<a href="#" class="btn">,点击时会触发a标签的默认跳转(跳转到页面顶部),打断弹窗逻辑,需要在点击事件中阻止该默认行为。
修改后的JS片段:
btn.addEventListener('click', (e) => { // 阻止a标签默认跳转行为 e.preventDefault(); videoContainer.classList.add('show'); });
完整修复后的代码
HTML(无需修改)
<div class="modal"> <img class="ellipse1" src="./images/Ellipse 1.png"> <img src="/images/Icon (double click to edit).png" alt="play"> <a href="#" class="btn"><p>Watch Demo <br>Video</p></a> <div class="video-container"> <iframe class="video" width="560" height="315" src="https://www.youtube.com/embed/6dNho0h_yQQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> <div class="close"> <img src="/images/close button.png"> </div> </div> <img class="line4" src="./images/Line 4.png"> </div>
CSS
.btn { text-decoration: none; z-index: 10; } .video-container { position: fixed; width: 100%; height: 100%; top: 0; left: 0; z-index: 99999; display: flex; justify-content: center; align-items: center; opacity: 0; pointer-events: none; transition: all 0.3s; /* 新增半透明背景,提升弹窗视觉层级 */ background-color: rgba(0,0,0,0.8); } .video-container .close { position: absolute; top: 10%; right: 25px; cursor: pointer; /* 给关闭按钮设置固定尺寸,优化点击体验 */ width: 40px; height: 40px; } .video-container .video { width: 90%; max-width: 800px; transform: scale(0); box-shadow: 0 20px 20px rgba(0, 0, 0, 0.2); outline: none; transition: all 0.3s; } .video-container.show { pointer-events: all; opacity: 1; } .video-container.show .video { transform: scale(1); }
JS
const btn = document.querySelector('.btn'); const videoContainer = document.querySelector('.video-container'); const close = document.querySelector('.close'); btn.addEventListener('click', (e) => { e.preventDefault(); videoContainer.classList.add('show'); }); close.addEventListener('click', () => { videoContainer.classList.remove('show'); }); // 额外优化:点击弹窗背景区域也关闭视频 videoContainer.addEventListener('click', (e) => { if(e.target === videoContainer) { videoContainer.classList.remove('show'); } });
内容的提问来源于stack exchange,提问作者Natalia
相关产品推荐
相关产品推荐

