修复了滚动div内的div

22 html javascript css jquery frontend

我需要使我的网站的主要有980px width500px height(class ="main")只有当鼠标在滚动div上并且有a height of 1500px和a width of 100%(class ="container-scroll")时才能修复,这是在其他div内部with height of 500px.(class ="container")

很困惑吧?

我做了一个小提琴,我几乎在那里,问题是,如果我设置主要固定,它将滚动页面,而不仅仅是在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>
Run Code Online (Sandbox Code Playgroud)

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;*/
    }
Run Code Online (Sandbox Code Playgroud)

Tii*_*iJ7 26

如果我正确理解这一点,你希望主div保持在父div的顶部?

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

做出的改变:

  • #wrapper .main:添加position:absolute("固定"到父级)
  • #wrapper .container-scroll:添加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";
}
Run Code Online (Sandbox Code Playgroud)


flo*_*bon 5

没有纯CSS可以做到这一点,但你可以用一些Javascript解决它.

一个解决方案可能是禁用内部滚动,div如果已经启动了滚动#wrapper,这是在这个小提琴演示:

https://jsfiddle.net/qmjmthbz/

这是代码:

var wrapper = $('#wrapper');
var container = $('.container');
var timer;

// Listen to mouse scroll events
$('body').on('mousewheel', function(e) {
    var target = $(e.target);
    /* If the scroll is initiated from the #wrapper,
       disable scroll on the container and re-enable it
       100ms after the last scroll event */
    if (target[0] === wrapper[0]) {
        container.addClass('no-scroll');
        clearTimeout(timer);
        timer = setTimeout(function() {
            container.removeClass('no-scroll');
        }, 100);
    }
});
Run Code Online (Sandbox Code Playgroud)

注意:使用jQuery实现这一点是没用的,但我在火车站赶紧去.当我能找到更多时间时,我会提供更好的代码:-)