简体   繁体   中英

How to scroll an element you are not focused in using jQuery?

How does sites like Pinterest and 9gag's fast version do this:

On Pinterest if you click on any image and get the modal you will notice that scrolling anywhere on the page causes the modal to scroll and not the main document.

On 9gag if you scroll anywhere except the comment section, it's the main content area on the left that scrolls.

In either case, you don't have to be focused on the area you would like to scroll. Just scrolling anywhere even if your mouse isn't inside the area you want to scroll, causes that area to be scrolled.

How do they achieve this? For example how can one disable scrolling on the main document and cause some div on the page to scroll in it's place?

On Pinterest, when a modal opens up, a class of "noscroll" is added to the <body/> :

.noscroll {overflow: hidden !important;}

This prevents the body from scrolling. The modal itself has an id of "zoomscroll" which contains the following:

overflow-y: scroll;

So while the body is frozen, the overflow of #zoomscroll can be scrolled.

Have a look at the demo here: http://jsbin.com/ucacon/2/edit — Click on any paragraph to freeze the body, and enable scrolling on the paragraph itself.

This is the actual CSS they have on their modal.

#zoomScroll {
    position: fixed;
    z-index: 9999;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: white;
    background-color: rgba(255, 255, 255, 0);
    overflow-x: auto;
    -y: scroll;
    -webkit-perspective: 1000;
}

That plus the body class noscroll makes it work.

.noscroll {overflow: hidden !important;}

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