滚动停止时恢复滚动位置

时间:2015-10-15 10:26:15

标签: javascript jquery scroll

Fiddle

我使用按钮滚动nagivation,但问题是当用户使用鼠标滚轮滚动时似乎有错误。所以为了解决这个问题,我想到了抓住滚动停止位置。我发现了这个

$.fn.scrollStopped = function(callback) {
  var that = this, $this = $(that);
  $this.scroll(function(ev) {
    clearTimeout($this.data('scrollTimeout'));
    $this.data('scrollTimeout', setTimeout(callback.bind(that), 250, ev));
  });
};

但不知道如何继续。

3 个答案:

答案 0 :(得分:1)

我不会检查滚动停止的时间,而是检查滚动的方向。我还添加了对点击功能的检查,因此scrollValue无法超出范围,导致按钮无效点击



var scrollValue = 0,
    scrollAmount = 60,
    ul = $('#numbers'),
    maxScroll = (ul.children('li').length * scrollAmount) - ul.height(),
    up = $('#up'),
    down = $('#down');

down.click(function () {
    if (scrollValue < maxScroll) {
        scrollValue += scrollAmount;
        ul.stop().animate({
            scrollTop: scrollValue
        });
    }
});

up.click(function () {
    if (scrollValue > 0) {
        scrollValue -= scrollAmount;
        ul.stop().animate({
            scrollTop: scrollValue
        });
    }
});

ul.on('mousewheel DOMMouseScroll', function (e) {
    e.preventDefault();
    if (!$(this).is(':animated')) {
        if (e.originalEvent.wheelDelta >= 0) {
            up.click();
        } else {
            down.click();
        }
    }
});
&#13;
ul {
    padding: 0;
    margin: 0;
    height: 180px;
    overflow: auto;
}
li {
    height: 50px;
    background: pink;
    list-style: none;
    margin-bottom: 10px;
    height: 50px;
}
body {
    padding: 0;
    margin: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="numbers">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
</ul>
<button id="up">up</button>
<button id="down">down</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我想你可能会找到一个完整的解决方案:

Demo

$(function() {

var itemheight = $('li').eq(0).outerHeight(true),
up, busy;

$('ul').on('wheel', function(e) {

    var direction = e.originalEvent.deltaY;

    if (direction < 0) up = true;
    else up = false;

    scrollIt();

    return false;
});

$('button').click(function() {

    if ($(this).text() == 'up') up = true;
    else up = false;

    scrollIt();
});

function scrollIt() {

    if (busy) return;
    busy = true;

    var current = $('ul').scrollTop();

    if (up) current -= itemheight;
    else current += itemheight;

    $('ul').animate({scrollTop: current}, 400, function() {

        busy = false;
    });
}
});

它会阻止动画的建立,并且会像按下按钮一样对待鼠标滚轮。

答案 2 :(得分:0)

不应存储scrollValue,而应计算ul的当前滚动并将scroll ammount添加到该值

var scrollValue = $('ul').scrollTop();
scrollValue = scrollValue + 60;

https://jsfiddle.net/dango_x_daikazoku/od00zxa0/

相关问题