最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - If scrollTop is greater than value, then do this ONLY ONCE - Stack Overflow

matteradmin7PV0评论

When user scrolls past 10px from the top, I'd like to hijack their scroll and scroll them down to certain div. After this happens once, I'd like to release the scroll to be free to scroll wherever. How do I do this?

My current code works but it won't let user to scroll freely after that initial scroll:

$(window).scroll(function() {

    //if I scroll more than 1000px...
    if($(window).scrollTop() > 10){
         $('html,body').animate({scrollTop : $('#main').offset().top}, 900, function(){
            h = 2; 
        });
    }
});

When user scrolls past 10px from the top, I'd like to hijack their scroll and scroll them down to certain div. After this happens once, I'd like to release the scroll to be free to scroll wherever. How do I do this?

My current code works but it won't let user to scroll freely after that initial scroll:

$(window).scroll(function() {

    //if I scroll more than 1000px...
    if($(window).scrollTop() > 10){
         $('html,body').animate({scrollTop : $('#main').offset().top}, 900, function(){
            h = 2; 
        });
    }
});
Share Improve this question asked Nov 9, 2015 at 23:07 beliy333beliy333 47912 silver badges26 bronze badges 1
  • whats the h = 2 for? – Paul Browne Commented Nov 9, 2015 at 23:09
Add a ment  | 

1 Answer 1

Reset to default 3

Try:

var scrolled = false;

$(window).scroll(function() {

    //if I scroll more than 1000px...
    if($(window).scrollTop() > 10 && scrolled == false){
         $('html,body').animate({scrollTop : $('#main').offset().top}, 900, function(){
            h = 2; 
        });
      scrolled = true;
    } else if($(window).scrollTop() == 0) {
      scrolled = false;
    }
});
Post a comment

comment list (0)

  1. No comments so far