问题描述:

I am working on new website, all in one page.

Now I have the main div that called "home", and the another page's divs that are called "colordiv".

now i am trying to switch between the divs by scrolling up and down.

this is my html:

 <div id="home" class="home_div">

//here home page code

</div>

<div id="color1" class="color_div" style="background-color:#253412;">

</div>

<div id="color2" class="color_div" style="background-color:#956341;">

</div>

and that is my jQuery code:

$("document").ready(function() {

$('#learnMbtn').click(function(){

$('html, body').animate({

scrollTop: $("#color1").offset().top

}, 600);

});

var lastScroll = 0;

var temp = $("div.color_div");

$(window).scroll(function(event){

//Sets the current scroll position

var st = $(this).scrollTop();

//Determines up-or-down scrolling

if (st > lastScroll){

$('html, body').animate({

scrollTop: temp.offset().top

}, 600);

temp = temp.next();

}

else {

//here the scroll up code(prev)

}

//Updates scroll position

lastScroll = st;

});

});

and this does not work for me, and I have no idea how to do the scroll up code, can you help me?

网友答案:

var temp = $("div.color_div"); this means the temp variable get a series of Elements which classname has color_div.

So, you use temp.offset().top below, jQuery don't get the current offset().top.

If the .color_div has id like #color1 #color2 or #colorN, maybe you can use the last number as counter and identity, like :

var counter = 1;
var temp = $("#color"+counter);
$(window).scroll(function(event){

    if (st > lastScroll){
        $('html, body').animate({
            scrollTop: temp.offset().top
        }, 600);
        counter++;
        temp = $("#color"+counter);
    }
    else {

        counter--;
        temp = $("#color"+counter);

    }

});
相关阅读:
Top