简体   繁体   中英

Scroll down or up is in infinity loop

I am trying to do the next thing:

在此处输入图片说明

In other words: there is some div-s. I want to display always X div-s. the three upper divs will be colored in black and the last div will be colored in gray.

If I scrolled down, the upper 3 divs will be colored in black and the last one will be colored in gray. (If scrolling up, the same thing happens: 3 upper divs will be colored in black, the last one in gray).

I don't know why the scroll event is called more then 1 time after scrolled down or up pressed (one press). It's in loop mode.

(After I fix it, I will do the color issue)

this is my jsfiddle:

http://jsfiddle.net/alonshmiel/Ht6Ym/2966/

and this is for the scroll:

jQuery(function($) {
    $('#divContent').scroll(function() {
        var currentScrollTop = $(this).scrollTop();
        if (currentScrollTop > divContentScrollTop) {
            divContentScrollTop += (divHeight + 2);
            $("#divContent").scrollTop(divContentScrollTop)
        }
        else {
            divContentScrollTop -= (divHeight + 2);
            $("#divContent").scrollTop(divContentScrollTop)
        }
    })
});

Any help appreciated.

It's because you are using javascript to scroll while you are in the scroll handler.

 $("#divContent").scrollTop(divContentScrollTop)

That is causing the div to scroll, which then fires the scroll handler, which then scrolls the div again, resulting in an endless loop.

You could change your code to remove the scrolling like this.

jQuery(function($) {
    $('#divContent').scroll(function() {
        var currentScrollTop = $(this).scrollTop();
        if (currentScrollTop > divContentScrollTop) {
            divContentScrollTop += (divHeight + 2);
        }
        else {
            divContentScrollTop -= (divHeight + 2);
        }
    })
});

Then keeping track of which div would be up top you can still do the coloring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM