smooth scroll to top

前端 未结 12 1158
眼角桃花
眼角桃花 2020-12-07 22:58

I\'ve bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors

相关标签:
12条回答
  • 2020-12-07 23:29

    also used below:

      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    
    0 讨论(0)
  • 2020-12-07 23:32

    I think the simplest solution is:

    window.scrollTo({top: 0, behavior: 'smooth'});
    

    If you wanted instant scrolling then just use:

    window.scrollTo({top: 0});
    

    Can be used as a function:

    // Scroll To Top
    
    function scrollToTop() {
    
    window.scrollTo({top: 0, behavior: 'smooth'});
    
    }
    

    Or as an onclick handler:

    <button onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>
    
    0 讨论(0)
  • 2020-12-07 23:36

    Came up with this solution:

    function scrollToTop() {
    let currentOffset = window.pageYOffset;
    const arr = [];
    
    for (let i = 100; i >= 0; i--) {
        arr.push(new Promise(res => {
                setTimeout(() => {
                        res(currentOffset * (i / 100));
                    },
                    2 * (100 - i))
            })
        );
    }
    
    arr.reduce((acc, curr, index, arr) => {
        return acc.then((res) => {
            if (typeof res === 'number')
                window.scrollTo(0, res)
            return curr
        })
    }, Promise.resolve(currentOffset)).then(() => {
        window.scrollTo(0, 0)
    })}
    
    0 讨论(0)
  • 2020-12-07 23:39

    You should start using jQuery or some other js lib. It's way easier than js, and you can use it as a shorthand for most js instead of actually long, drawn out js.

    Simply put <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> (or whatever the latest google cdn is https://developers.google.com/speed/libraries/devguide#jquery) in your <head>.

    Then, inside your event code (much easier if you use jQuery: $.click() for buttons, $.change() for checkboxes, selects, radios...), put the code from your second link looking more like

    $('#theIDofTheButtonThatTriggersThisAnimation').click(function(){
        $('#theIDofTheElementYouWantToSmoothlyScroll').animate({
            scrollTop: 0
        }, 2000);
    });
    

    However, if you're trying to do animations, I recommend you look into some basic css properties like position:absolute and position:relative to keep from going crazy.


    I'm still not quite sure what's going on in your code because it's very non-standard relative to how things are done now with css & jQuery. I'd break it down into something simple to learn the general concept.

    For your example, you should build off of my animation example, how I learned: https://stackoverflow.com/a/12906254/1382306

    I think you're trying to move your text up and down based upon a $.click(). In the fiddle in my answer, it slides left and right. You can easily reformat up and down by using the css top property instead of left.

    Once you figure out how to move the entire div up and down, you can make a relative container to hold all of the content absolute divs and manipulate all content divs with a loop by setting their tops. Here's a quick primer on absolute in relative: http://css-tricks.com/absolute-positioning-inside-relative-positioning/

    All of my animations have relative containers and absolute content. It's how I made a custom gridview plugin that can instantly zip through an entire database.

    Also, there really is no overuse of divs when it comes to animating. Trying to make 1 div do everything is a nightmare.

    Try to see if you can reformat my fiddle into a vertical slide out. Once you've done that, research absolute in relative a little. If you have any more problems, just ask another question.

    Change your thinking to these philosophies, and you'll start flying through this type of coding.

    0 讨论(0)
  • 2020-12-07 23:44

    You can simply use

    // When the user scrolls down 20px from the top of the document, show the button
    window.onscroll = function() {scrollFunction()};
    
    function scrollFunction() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            document.getElementById("gotoTop").style.display = "block";
        } else {
            document.getElementById("gotoTop").style.display = "none";
        }
       
    }
    
    // When the user clicks on the button, scroll to the top of the document
    function topFunction() {
     
         $('html, body').animate({scrollTop:0}, 'slow');
    }
    body {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 20px;
    }
    
    #gotoTop {
      display: none;
      position: fixed;
      bottom: 20px;
      right: 30px;
      z-index: 99;
      font-size: 18px;
      border: none;
      outline: none;
      background-color: red;
      color: white;
      cursor: pointer;
      padding: 15px;
      border-radius: 4px;
    }
    
    #gotoTop:hover {
      background-color: #555;
    }
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    
    <button onclick="topFunction()" id="gotoTop" title="Go to top">Top</button>
    
    <div style="background-color:black;color:white;padding:30px">Scroll Down</div>
    <div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>

    0 讨论(0)
  • 2020-12-07 23:44

    I just customized BootPc Deutschland's answer

    You can simply use

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $('body,html').animate({
                scrollTop: 0
            }, 800);
        $('#btn-go-to-top').click(function () {
            $('body,html').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    }); 
    </script>
    

    this will help you to smoothly scroll to the top of the page.

    and for styling

    #btn-go-to-top {
    opacity: .5;
    width:4%;
    height:8%;
    display: none;
    position: fixed;
    bottom: 5%;
    right: 3%;
    z-index: 99;
    border: none;
    outline: none;
    background-color: red;
    color: white;
    cursor: pointer;
    padding: 10px;
     border-radius: 50%;
    }
    
    #btn-go-to-top:hover {
    opacity: 1;
    }
    .top {
    transition: all 0.5s ease 0s;
    -moz-transition: all 0.5s ease 0s;
    -webkit-transition: all 0.5s ease 0s;
    -o-transition: all 0.5s ease 0s;
    }
    

    this styling makes the button arrive at the bottom-right of the page.

    and in your page you can add the button to go to top like this

    <div id="btn-go-to-top" class="text-center top">
    <img src="uploads/Arrow.png" style="margin: 7px;" width="50%" height="50%">
    </div>
    

    hope this help you.if you have any doubts you are always free to ask me

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