Fixed div inside scrolling div

拥有回忆 提交于 2019-12-03 09:44:35

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

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

Changes made:

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

There is no pure CSS to do that, but you could work around it with some Javascript.

One solution could be to disable scrolling on the inner div if the scrolls has been initiated on the #wrapper, which is demoed on this fiddle:

https://jsfiddle.net/qmjmthbz/

Here is the code:

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

Note: it is useless to use jQuery to achieve that but I am rushing that at a train station. I will provide a better code when I can find more time :-)

Basicly I think you can't make the div scroll because the content of the div does not exceed the height of the div. In order for the div to become scroll-able the content should actually exceed the height of the div.

Try giving the div a height of lets say 100px, and insert an amount of text large enough to exceed the 100px height, thus making the div scrollable, and then try if what you want to achieve works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!