开发者

Scroll down the page automatically until the user scrolls up

I got this simple script to scroll down the page

function scrollDown() {
     window.scrollBy(0,50); // horizontal and vertical scroll increments
}

scrolldelay = setTimeout('scrollDown()',100); // scrolls every 100 milliseconds

Now I wish to intercept when the user scrolls up himself to stop the setTimeout with a

clearTimeout(开发者_C百科scrolldelay);

Any idea? Preferable with pure js

An alternative to accepted answer is here: http://jsfiddle.net/Vy8tW/


var start = (function() {
    function scrollTop() {
        return window.scrollTop || document.body.scrollTop || (document.documentElement && document.documentElement.scrollTop)
    }

    var top = scrollTop();
    var interval;
    window.onscroll = function() {
        var newtop = scrollTop();
        if (newtop < top) {
            clearInterval(interval);
        }
        top = newtop;
    };
    return function() {
        interval = setInterval(function() {
            window.scrollBy(0, 50);
        }, 100);
    }
}());

start();

How it works: Each time the page is scrolled, it compares the current scrollTop to the previous one. If we detect that the page has been scrolled up, we stop the interval.

You can re-start the scroll by calling start() again.

Try it here: http://jsfiddle.net/fR9Wt/3/


You need to capture the scroll event from the user.

If you're using jquery (or perhaps a similar library that offers similar functionality) you can detect it with .scroll()

$('#target').scroll(function() {
    clearInterval(scrolldelay);
});

Otherwise, you'll need to capture the scroll event yourself. If this intended for cross-browser use, the event naming scheme will be "scroll" for standard browsers, and "onscroll" for IE.

This page has some very basic examples, http://help.dottoro.com/ljurkcpe.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜