Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

javascript - Resume scroll position upon scroll stop

Fiddle

I did scroll nagivation using buttons, but the problem is it seems buggy when the user scrolls using their mousewheel. So to solve this I thought of catching the scroll stop position. I found this

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

But don't know how to continue.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of checking when the scroll has stopped, I would check the direction of the scroll instead. I have also added checking into the click functions so the scrollValue can't go out of range leading to dead clicks of your buttons

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...