可滚动div内部按钮无法固定相对位置,请问代码哪里存在问题
问题原因
你当前的外层容器同时承担了「绝对定位上下文」和「可滚动内容容器」两个职能:容器开启了overflow: auto时,内部所有内容(包括设置了position: absolute的子元素)都会作为滚动内容的一部分,随滚动条移动。
解决方案
拆分容器职责,分为两层结构:外层仅作为定位父级固定位置,内层承载可滚动内容:
- 拆分原容器的两个类对应不同层级:外层保留
dt-baseContainer类,负责定位、定义容器尺寸,不设置滚动属性;内层新增单独的dt-container节点,负责承载滚动内容、开启滚动属性、设置背景边框样式。 - 将固定定位的按钮和滚动内容容器平级,放在外层
dt-baseContainer内部。
修正后完整代码
<!DOCTYPE html> <html> <head> <title>Scroll</title> <meta charset='utf-8'/> <style> div.dt-baseContainer { width: 50vw; height: 50vh; min-width: 400px; min-height: 300px; left: 50%; top: 50%; transform: translate(-50%,-50%); position: absolute; border-radius: 20px; } div.dt-container { width: 100%; height: 100%; box-sizing: border-box; overflow: auto; background-color: lightblue; border: 3px solid royalblue; text-align: center; border-radius: inherit; } button.dt-quit { border-style: solid; border-radius: 4px; border-color: inherit; width: 20px; height: 20px; background-color: white; color: red; font-weight: bold; font-size: 12px; text-align: center; margin: 0; padding: 0; z-index: 20; top: 5px; right: 5px; position: absolute; cursor: pointer; } </style> </head> <body> <div class='dt-baseContainer' id='dt_container'> <div class='dt-container'> sdfsdf1<br>sdfsdf2<br>sdfsdf3<br>sdfsdf4<br>sdfsdf5<br>sdfsdf6<br>sdfsdf7<br>sdfsdf8<br>sdfsdf9<br>sdfsdf10<br> sdfsdf11<br>sdfsdf12<br>sdfsdf13<br>sdfsdf14<br>sdfsdf15<br>sdfsdf16<br>sdfsdf17<br>sdfsdf18<br>sdfsdf19<br>sdfsdf20<br> sdfsdf20<br>sdfsdf21<br>sdfsdf22<br>sdfsdf23<br>sdfsdf24<br>sdfsdf25<br>sdfsdf26<br>sdfsdf27<br>sdfsdf28<br>sdfsdf30<br> </div> <button id='dt_quit' class='dt-quit' title='Stop'>X</button> </div> </body> </html>
内容的提问来源于stack exchange,提问作者ACProctor
相关产品推荐
相关产品推荐

