修复了滚动 div 内的 div

2022-01-19 00:00:00 frontend jquery javascript html css

我需要只在鼠标悬停在滚动条上时修复具有 980px 宽度500px 高度 (class="main") 的网站的主要部分div 的 height 为 1500pxwidth 为 100% (class="container-scroll"),它位于其他 div 中,height 为 500px. (class="container")

I need to make the main of my site that has 980px width and 500px height (class="main") be fixed only when the mouse is over a scrolling div and has a height of 1500px and a width of 100% (class="container-scroll"), that is inside other div with height of 500px. (class="container")

很困惑,对吧?

我做了一个fiddle,我快到了,问题是如果我将main设置为fixed,它会随着页面滚动,而不仅仅是div内部

I made a fiddle, I'm almost there, the problem is that if I set up the main to fixed, it will scroll with the page , not just inside the div

这是我的小提琴: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 的顶部吗?

If I'm understanding this correctly, you want the main div to stay on the top of the parent div?

小提琴:https://jsfiddle.net/8oj0sge4/3/ (完整)

所做的更改:

  • #wrapper .main:添加了position:absolute(固定"到父级)
  • #wrapper .container-scroll:添加 position: relative(确定要修复"到哪个父级)
  • 在主 div 中添加了一个 id(为方便起见)
  • #wrapper .main: Added position:absolute ("fixed" to parent)
  • #wrapper .container-scroll: Added position: relative (determines what parent to "fix" to)
  • Added an id to the main div (for convenience)

JavaScript 代码:

JavaScript code:

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";
}

相关文章