简体   繁体   中英

Fixed div while scrolling

At a point of my page , I have a div 100% width containing 2 divs in float , 50% width each , one of them has a bigger height then the main div , but the overflow is set scroll. So what I need is that when I scroll my page , and I arrive at the div containing the 2 divs , the page scroll stops , and scrolls only the div with overflow set scrolling , and after I finish scrolling that div , my page can start scrolling again..

Just a snippet to show how it 'could' be done. Myself I wouldn't use this, since listening for each scroll event can be very costly in performance.

var div = document.querySelector('yourDivReference'),
    focussed = false;
window.addEventListener('scroll', function ( event ) {
    if (!focussed && window.pageYOffset >= (div.offsetTop - 2)) {
        div.focus();
        focussed = true;
    }
});

Tested on IE. In other browsers you might have to use different properties than offsetTop and pageYOffset. The idea is that you calculate how much the window has scrolled. Once you get to the scrollable div location, you put the focus on the div so that the div will scroll instead. You can add the opposite yourself, where you check the end of the div scrolling, so you can switch focussed back to false, put focus back on the body and then continue scrolling there. Don't forget to put a tab-index on any element you want to focus. You might have to wrap the floating elements into another non-floating container if they don't give accurate positions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM