如何控制另一个div内的可滚动div的位置?

时间:2014-09-24 14:49:42

标签: jquery scroll overflow

我试图使可滚动的内部div跳回到底部,但是.css()和.animate()似乎都不起作用。

http://jsfiddle.net/1yzpot2b/



var $fixedHolder = $('#fixedHolder'),
    $slidingHolder = $('#slidingHolder');

$fixedHolder.on('scroll', function onScroll() {
    var scrollTop = $fixedHolder.scrollTop();

    console.log('scrollTop', scrollTop);

    if (scrollTop >= 290) {
        console.info('jump up');

        $fixedHolder.off('scroll');

        $slidingHolder.css({
            top: '10px'
        });

        $slidingHolder.animate({
            scrollTop: 0
        }, 200);
    }
});

#fixedHolder {
    width: 30px;
    height: 100px;
    overflow-y: scroll;
    border: 1px solid #ccc;
    position: relative;
}
#slidingHolder {
    position: absolute;
}

<div id="fixedHolder">
    <div id="slidingHolder">a b c d e f g h i j k l m n o p q r s t v z x</div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我并非100%确定您要尝试实现的目标,但您似乎正在尝试设置错误元素的scrollTopscrollTop 290的价值太大了。您可以通过取$slidingHolder的高度减去$fixedHolder高度来计算此最大滚动高度。

请参阅:http://jsfiddle.net/1yzpot2b/3/或运行代码段:

&#13;
&#13;
var $fixedHolder = $('#fixedHolder'),
    $slidingHolder = $('#slidingHolder');

$fixedHolder.on('scroll', function onScroll() {
    var scrollTop = $fixedHolder.scrollTop();

    console.log('scrollTop', scrollTop);

    var maxScroll = $slidingHolder.height() - $fixedHolder.height();
    if (scrollTop >= maxScroll) {
        console.info('jump up');
        /*
        dunno about these :
        $fixedHolder.off('scroll');

        $slidingHolder.css({
            top: '10px'
        });
        */
        $fixedHolder.animate({
            scrollTop: 0
        }, 200);
    }
});
&#13;
#fixedHolder {
    width: 30px;
    height: 100px;
    overflow-y: scroll;
    border: 1px solid #ccc;
    position: relative;
}
#slidingHolder {
    position: absolute;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="fixedHolder">
    <div id="slidingHolder">a b c d e f g h i j k l m n o p q r s t v z x</div>
</div>
&#13;
&#13;
&#13;