且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在div中滚动而不移动页面

更新时间:2023-11-01 21:17:16

jsfiddle 适用于Chrome。未在其他浏览器中测试过。

捕捉mousewheel事件,使用事件数据手动滚动,然后取消原始事件。看起来可能会产生混乱。



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

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

//防止滚动页面
返回false ;
});


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!

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