简体   繁体   中英

show/hide div using scrollTop

I'm trying to create a script which would show div if 500px < scrollTop < 800px otherwise it would be hidden. So if my scroll is from 0 to 500 and from 800 and more it is hidden and between 500 and 800 it is shown. I'm new to javascript but this is what I have tried:

$(document).ready(function(){ 

$(window).scroll(function(){
    if ($(this).scrollTop() > 500) {
        $('.myDiv').fadeIn();
    } else {
        $('.myDiv').fadeOut();
    }
    if ($(this).scrollTop() > 800) {
        $('.myDiv').fadeOut();
    }
});

However after scrolling to 800 it bugs and starts endlessly hiding and showing. Any way to fix it please?

$(window).scroll(function(){

    if ($(this).scrollTop() > 800) {
        $('.myDiv').fadeOut();
    }
    else {
       if ($(this).scrollTop() > 500) {
           $('.myDiv').fadeIn();
       } else {
           $('.myDiv').fadeOut();
       }
    }

});

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