滚动div一定数量的像素:如何滚动div而不会导致滚动事件

时间:2014-06-19 15:41:39

标签: javascript jquery scroll

当用户滚动可滚动的div(列表)时,我希望它能够精确滚动列表项的1个高度(22px)。 我遇到的问题是,如果我处理$(element).scroll事件并在其中执行$(element).scrollTop(previousScrollTop + 22),将触发新的“scroll”事件,并且将递归地再次调用我的处理程序。

请看一下这个例子: http://jsfiddle.net/VAFkk/1/

  

如何实现一定数量像素的滚动?
  我怎么能够   更改scrollTop而不触发“scroll”事件?

不胜感激任何建议。 使用JQuery 1.9.1。

JavaScript的:

var previousScrollTop = $('.list').scrollTop();

// Bind scroll handler so that it scrolls exactly 22px.
$('.list').scroll(function() {
    console.log('scroll happened');
    var listElement = $(this);
    var currentScrollTop = listElement.scrollTop();

    if (currentScrollTop > previousScrollTop) {
        listElement.scrollTop(previousScrollTop + 22);
    } else if (currentScrollTop < previousScrollTop) {
        listElement.scrollTop(previousScrollTop - 22);
    }

    previousScrollTop = currentScrollTop;
});

HTML:

<div class="list">
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
    <div class="list-item"></div>
</div>

CSS:

.list {
    border: 1px solid red;
    max-height: 88px;
    overflow-y: auto;
}

.list-item {
    border: 1px solid blue;
    height: 20px;
}

1 个答案:

答案 0 :(得分:2)

(function (step) { // capture variables so you don't pollute
    var prev = $('.list').scrollTop(),
        ignore_scroll = false; // flag
    // declare what we want to do
    function scroll_function(e) {
        var me, cur;
        // if flag true, don't do anything more
        if (ignore_scroll) return;
        // get vars after check (saves needless calls)
        me = $(this),
        cur = me.scrollTop();
        // set flag
        ignore_scroll = true;
        // do stuff
        if (cur > prev) me.scrollTop(prev += step);
        else if (cur < prev) me.scrollTop(prev -= step);
        // unset flag
        ignore_scroll = false;
        /* optional bonus, fix odd ends
        prev = prev - (prev % step)
        */
    }
    // add handler
    $('.list').scroll(scroll_function);
}(22)); // invoke