在div外滚动将滚动内容

时间:2012-11-19 23:29:24

标签: javascript jquery html css scroll

我怎样才能在div之外滚动操作,并且操作将被分配给固定div,在我的情况下隐藏溢出是#scrollable_content。

HTML

<div id="container">
<div id="header">Header</div>        
    <div id="scrollable_content">
        Very long content<br />
        Very long content<br />
        ...
        Very long content<br />
        Very long content<br />        
    </div>
<div id="footer">Footer</div>

CSS

html, body {
    height:100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
}
div { margin: 0; padding: 0;}
div#header{position:absolute;top:0;width:100%;border:1px solid black;}
div#footer{position:absolute; bottom:0; width:100%; border:1px solid black;}

div#scrollable_content {
    height: 300px;
    overflow-y:auto;
    position: static;
    border: 1px solid green;
    margin: 150px;
}

这是示例http://jsfiddle.net/gtyBn/

2 个答案:

答案 0 :(得分:2)

这段代码可以解决问题,但您可能需要调整处理程序的工作方式。大部分代码来自http://www.adomas.org/javascript-mouse-wheel/,但我确实修改了句柄功能以满足您的需求。

/** This is high-level function.
 * It must react to delta being more/less than zero.
 */
function handle(delta) {
    var target = $('#scrollable_content');
    var top = target.scrollTop() - delta;
    target.scrollTop(top);
}

/** Event handler for mouse wheel event.
 */
function wheel(event){
    var delta = 0;
    if (!event) /* For IE. */
            event = window.event;
    if (event.wheelDelta) { /* IE/Opera. */
            delta = event.wheelDelta/120;
    } else if (event.detail) { /** Mozilla case. */
            /** In Mozilla, sign of delta is different than in IE.
             * Also, delta is multiple of 3.
             */
            delta = -event.detail/3;
    }

    /** If delta is nonzero, handle it.
     * Basically, delta is now positive if wheel was scrolled up,
     * and negative, if wheel was scrolled down.
     */
    if (delta) handle(delta);

    /** Prevent default actions caused by mouse wheel.
     * That might be ugly, but we handle scrolls somehow
     * anyway, so don't bother here..
     */
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}


if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;

答案 1 :(得分:1)

尝试使用鼠标滚轮http://brandonaaron.net/code/mousewheel/demos,或者你可能会找到其他一些,甚至创建自己的解决方案,但它看起来像工作方向