scroll up and down a div on button click using jquery

前端 未结 7 1427
梦毁少年i
梦毁少年i 2020-12-02 15:14

I am trying to add a feature to scroll up and down a div based on button click. I was able to do the scroll down part easily, but got stuck wit the scroll up part and one mo

相关标签:
7条回答
  • 2020-12-02 15:19

    To solve your other problem, where you need to set scrolled if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:

    var timer = 0;
    $(window).scroll(function() {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(function() {
        scrolled = $(window).scrollTop();
      }, 250);
    });
    
    0 讨论(0)
  • 2020-12-02 15:25

    You can use this simple plugin to add scrollUp and scrollDown to your jQuery

    https://github.com/phpust/JQueryScrollDetector

    0 讨论(0)
  • 2020-12-02 15:27

    For the go up, you just need to use scrollTop instead of scrollBottom:

    $("#upClick").on("click", function () {
        scrolled = scrolled - 300;
        $(".cover").stop().animate({
            scrollTop: scrolled
        });
    });
    

    Also, use the .stop() method to stop the currently-running animation on the cover div. When .stop() is called on an element, the currently-running animation (if any) is immediately stopped.

    FIDDLE DEMO

    0 讨论(0)
  • 2020-12-02 15:28

    Scrolling div on click of button.

    Html Code:-

     <div id="textBody" style="height:200px; width:600px; overflow:auto;">
        <!------Your content---->
     </div>
    

    JQuery code for scrolling div:-

    $(function() {
       $( "#upBtn" ).click(function(){
          $('#textBody').scrollTop($('#textBody').scrollTop()-20);
     }); 
    
     $( "#downBtn" ).click(function(){
         $('#textBody').scrollTop($('#textBody').scrollTop()+20);;
     }); 
    
    });
    
    0 讨论(0)
  • 2020-12-02 15:32

    Just to add to other comments - it would be worth while to disable scrolling up whilst at the top of the page. If the user accidentally scrolls up whilst already at the top they would have to scroll down twice to start

    if(scrolled != 0){
      $("#upClick").on("click" ,function(){
         scrolled=scrolled-300;
            $(".cover").animate({
              scrollTop:  scrolled
         });
      });
    }
    
    0 讨论(0)
  • 2020-12-02 15:42

    scrollBottom is not a method in jQuery.

    UPDATED DEMO - http://jsfiddle.net/xEFq5/10/

    Try this:

       $("#upClick").on("click" ,function(){
         scrolled=scrolled-300;
            $(".cover").animate({
              scrollTop:  scrolled
         });
       });
    
    0 讨论(0)
提交回复
热议问题