修复了滚动 div 内的 div

2024-01-01

我需要使我的网站的主体具有980px width and 500px height(class="main") 仅当鼠标位于滚动 div 上并且具有height of 1500px and a width of 100%(class="container-scroll"),即在其他 div 内height of 500px.(类=“容器”)

很困惑,对吧?

我做了一个小提琴,我就快到了,问题是,如果我将 main 设置为固定,它将随页面滚动,而不仅仅是在 div 内滚动

这是我的小提琴:https://jsfiddle.net/8oj0sge4/1/embedded/result/ https://jsfiddle.net/8oj0sge4/1/embedded/result/

HTML:

<div id="wrapper">
    <div class="container">
        <div class="container-scroll">
            <div class="main">

            </div>
        </div>
    </div>
</div>

CSS:

    #wrapper {
        width: 100%;
        height: 1500px;
        border: 1px solid red;
        padding-top: 380px;
    }
    #wrapper .container {
        border: 1px solid green;
        width: 100%;
        height: 500px;
        overflow: scroll;
    }
    #wrapper .container-scroll {
        height: 1500px;
        width: 100%;
        border: 1px solid yellow;
    }
    #wrapper .main {
        width: 980px;
        height: 500px;
        background: black;
        overflow: scroll;
        /*position: fixed;*/
    }

如果我理解正确的话,您希望主 div 保持在父 div 的顶部吗?

Fiddle: https://jsfiddle.net/8oj0sge4/3/ https://jsfiddle.net/8oj0sge4/3/ (full https://jsfiddle.net/8oj0sge4/3/embedded/result/)

所做的更改:

  • #wrapper .main: Added position:absolute(“固定”给父级)
  • #wrapper .container-scroll: Added position: relative(确定要“修复”的父级)
  • 在主div中添加了一个id(为了方便)

JavaScript 代码:

var main = document.getElementById('main-site');
var maxTop = main.parentNode.scrollHeight-main.offsetHeight; // Make sure we don't go outside the parent

main.parentNode.parentNode.onscroll = function() {
   main.style.top = Math.min(this.scrollTop,maxTop) + "px";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

修复了滚动 div 内的 div 的相关文章

随机推荐