Scrolling within a div without moving page

可紊 提交于 2019-11-28 05:04:30

问题


I have a <div id="innerContent"> with overflow-y:scroll;. Links to anchors within innerContent are located on parent page, not in the div.

So far, I have tried anchors and scrollto's to attempt to scroll within the content. They both complete the scroll, but innerContent's height is larger than the browser window, so the entire parent page also scrolls to the anchor when the links are clicked.

Is there a way to do this with javascript, without moving the parent page? I do not have control over the height of the div - this is someone else's design.

This came close... but there isn't an answer here. How to automatic scroll inline div without scrolling the whole page?

Thank you!


回答1:


This jsfiddle works in Chrome for me. Not tested in other browsers.

Catches the mousewheel event, uses the event data to scroll manually, then cancels the original event. Seems potentially messy for production.

$('#scroll').bind('mousewheel', function(e){

    $(this).scrollTop($(this).scrollTop()-e.originalEvent.wheelDeltaY);

    //prevent page fom scrolling
    return false;    
});



回答2:


Use a fixed layout. In this jsfiddle I have a working example for it. Study the css. You don't need javascript for it.




回答3:


Inspired by Morlem's code, but working the other way around: stop the propagation only if scrolling out. In pure JS:

container.addEventListener('mousewheel', function(e) {
    var scrollingOverTheTop = (e.wheelDelta > 0 && this.scrollTop == 0);
    var scrollingOverTheBottom = (e.wheelDelta < 0 && (this.scrollTop >= this.scrollHeight - this.offsetHeight));
    if (scrollingOverTheBottom || scrollingOverTheTop) {
        e.preventDefault();
        e.stopPropagation();
    }
}, true);



回答4:


And if you do decide to use javascript (again, like KooiInc said, if you don't need js, don't use it), you can try using event.cancelBubble = true, which would prevent the event from propagating to the parent container so the page would not see your inner-div scrolling. Additional command you can use is event.preventDefault(), which prevents browser from triggering default behavior (i.e. scrolling) to the event.




回答5:


I just solved my issue with this by creating the following in CSS:

body.scroll_locked {
    height: 100%;
    width: 100%;
    overflow: hidden;
}

Then, when I show my modal/lightbox, which is JavaScript (jQuery), I add the scroll_locked class to the body to lock it in place and remove the class to go back. Seems like you could do the same for a mouseenter/mouseleave event for a div that's always on the page and you want to have the same effect.

$('body').addClass('scroll_locked');
$('body').removeClass('scroll_locked');


来源:https://stackoverflow.com/questions/6347333/scrolling-within-a-div-without-moving-page

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