scrolltop with animate not working

后端 未结 6 807
梦毁少年i
梦毁少年i 2020-12-01 11:53

I\'m trying to animate while scrolling but no luck with my code...

I have this jquery

$(window).scrollTop(200);

Now wanted to give

相关标签:
6条回答
  • 2020-12-01 12:27

    you just need to add pixel

    $('body').animate({ scrollTop: "300px" }, 1000);
    
    0 讨论(0)
  • 2020-12-01 12:28

    You have to use $('html,body') instead of $(window) because window does not have a scrollTop property.

    $('#scroll-bottom').on('click', function() {
      $('html, body').animate({
        scrollTop: 2000
      }, 2000); // for all browsers
      
      // $('html').animate({scrollTop: 2000}, 2000); // works in Firefox and Chrome
      // $('body').animate({scrollTop: 2000}, 2000); // works in Safari
    })
    #top {
      margin-bottom: 2000px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="top">
      <button id="scroll-bottom">scroll</button>
    </div>
    <div>bottom</div>

    0 讨论(0)
  • 2020-12-01 12:30

    if you have html and body style height:100%; its not working use

    height: auto;
    min-height: 100%;
    
    0 讨论(0)
  • 2020-12-01 12:32

    I'm using Angular and was trying to scroll down to an item that had been added in an ng-repeat. I put this code inside a $timeout (with zero time, just to make it happen after the elements displayed) and this was sufficient for the new item to have an offset().top...

    ...but I think there was just way too much going on adding dozens of new elements, so it didn't have the processing power to scroll-animate. When I set the timeout time to 1 second, it worked (though it actually took 7 seconds before the timeout got called).

    I concluded that animated, smooth scrolling won't really be tractable here, and instead I'm just using

    document.body.scrollTop = entry.offset().top
    
    0 讨论(0)
  • 2020-12-01 12:36

    DEMO

    <html>
    function scrollmetop(dest){
        var stop = $(dest).offset().top;
        var delay = 1000;
        $('body,html').animate({scrollTop: stop}, delay);
        return false;
    }
    
    scrollmetop('#test');
    <body>
        <div style="margin: 100px 100px 1000px 100px">
           <div id="test" style="width: 100px; height: 100px; border: 3px solid black;">target object</div>
        </div>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-01 12:37

    I had this problem as well and realised that the problem was within the CSS.

    In my case, I needed to remove the overflow-x: hidden; from the HTML tag.

    Remove:

    html {
        overflow-x: hidden;
    }
    

    Then, it worked.

    Hope that helps someone!

    0 讨论(0)
提交回复
热议问题