【CSS技巧系列】解决子容器滚动引发父容器滚动问题

背景描述

有些时候子容器和父容器都有滚动,子容器滚动到尽头的时候父容器会触发滚动,更有甚者有可能会触发谷歌浏览器的双指回退,那么你知道该怎么解决嘛?

解决方案

html,body{
    
    
    overscroll-behavior:none
}

案例演示

<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>overscroll-behavior-x demo</title>
    <style>
        main {
      
      
            height: 500px;
            width: 3000px;
            background-color: magenta;
            background-image: repeating-linear-gradient(to right, rgba(0, 0, 0, 0) 0px, rgba(0, 0, 0, 0) 19px, rgba(0, 0, 0, 0.5) 20px);
        }

        main>div {
      
      
            height: 300px;
            width: 500px;
            overflow: auto;
            position: relative;
            top: 100px;
            left: 100px;
            /*核心代码*/
            overscroll-behavior-x: contain;
        }

        div>div {
      
      
            height: 100%;
            width: 1500px;
            background-color: yellow;
            background-image: repeating-linear-gradient(to right, rgba(0, 0, 0, 0) 0px, rgba(0, 0, 0, 0) 19px, rgba(0, 0, 0, 0.5) 20px);
        }

        p {
      
      
            padding: 10px;
            background-color: rgba(255, 0, 0, 0.5);
            margin: 0;
            width: 300px;
            position: relative;
            top: 10px;
            left: 10px;
        }
    </style>
</head>

<body>
    <h1>overscroll-behavior-x demo</h1>
    <main>
        <div>
            <div>
                <p><code>overscroll-behavior-x</code>已经被用来使它在滚动边界时到达内框时,整个页面不会开始滚动</p>
            </div>
        </div>
    </main>
</body>
</html>

试一下这个案例,当你在黄色区域横向滚动的时候,粉色长条区域不会随之滚动。然后请你把overscroll-behavior-x: contain;注释掉,然后在黄色区域滚动=>看看会有什么样的效果

参考文档

overscroll-behaviorMDN文档

猜你喜欢

转载自blog.csdn.net/chengqige/article/details/126622220
今日推荐