纯CSS弹窗关闭时页面自动滚动至顶部的问题求助
解决纯CSS弹窗关闭时页面回到顶部的问题
嘿,我完全懂你遇到的困扰——纯CSS做弹窗本来就够折腾了,结果关闭的时候页面还自动跳回顶部,这体验真的糟透了。
问题根源
你原来的方案用了:target伪类来控制弹窗显示,关闭按钮的href="#"是罪魁祸首:浏览器会把#解析为“跳转到页面顶部锚点”,所以点击关闭时就会触发页面滚动。
纯CSS解决方案:用Checkbox替代:target
我们可以换一种思路,用隐藏的checkbox的checked状态来控制弹窗的显示/隐藏,完全不用JS,也不会触发页面滚动。
修改后的HTML代码
<div class="box"> <label class="button" for="popup-toggle">Show Overlay</label> <input type="checkbox" id="popup-toggle" hidden> </div> <div class="overlay"> <div class="popup"> <h2>Title</h2> <label class="close" for="popup-toggle">×</label> <div class="content">Content</div> </div> </div>
修改后的CSS代码
/*pop up overlay */ .box { width: 20%; margin: 0 auto; background: rgba(255, 255, 255, 0.2); padding: 35px; border: 2px solid #fff; border-radius: 20px/50px; background-clip: padding-box; text-align: center; } .button { font-size: 1em; padding: 10px; color: #fff; border: 2px solid blue; border-radius: 20px/50px; text-decoration: none; cursor: pointer; transition: all 0.3s ease-out; display: inline-block; /* 让label表现得和a标签一致 */ } .button:hover { background: blue; } .overlay { position: fixed; top: 0; bottom: 0; left: 0; right: 0; background: rgba(0, 0, 0, 0.7); transition: opacity 500ms; visibility: hidden; opacity: 0; } /* 用checkbox的checked状态触发弹窗显示 */ #popup-toggle:checked ~ .overlay { visibility: visible; opacity: 1; } .popup { margin: 70px auto; padding: 20px; background: #fff; border-radius: 5px; width: 30%; position: relative; transition: all 0.5s ease-in-out; /* 把原来的5s调整为更合理的0.5s */ } .popup h2 { margin-top: 0; color: #333; font-family: Tahoma, Arial, sans-serif; } .popup .close { position: absolute; top: 20px; right: 30px; transition: all 200ms; font-size: 30px; font-weight: bold; text-decoration: none; color: #333; cursor: pointer; /* 给label加上光标样式 */ } .popup .close:hover { color: orange; } .popup .content { max-height: 30%; overflow: auto; }
方案说明
- 我们用
<label>替代了原来的<a>标签,点击label会触发关联的checkbox状态切换 - 隐藏的checkbox的
checked状态通过CSS兄弟选择器~来控制弹窗的显示/隐藏 - 整个过程没有使用锚点跳转,所以完全不会出现页面回到顶部的问题
试试这个方案,应该就能完美解决你的问题啦!
内容的提问来源于stack exchange,提问作者wswswswsws
相关产品推荐
相关产品推荐

