Cross browser JavaScript (not jQuery…) scroll to top animation

后端 未结 20 865
抹茶落季
抹茶落季 2020-11-22 11:01

I\'m looking for a simple, cross-browser \"scroll to top\" animation I can apply to a link. I don\'t want to require a JS library such as jQuery/Moo, etc.

//         


        
相关标签:
20条回答
  • 2020-11-22 11:53

    I have choose @akai version of @timwolla answer and added stopAnimation function in return, so before starting new animation, the old one can be stopped.

    if ( this.stopAnimation )
        this.stopAnimation()
    
        this.stopAnimation = scrollTo( el, scrollDestination, 300 )
    
    
    // definitions
    
    function scrollTo(element, to, duration) {
        var start = element.scrollTop,
            change = to - start,
            increment = 20,
            timeOut;
    
        var animateScroll = function(elapsedTime) {        
            elapsedTime += increment;
            var position = easeInOut(elapsedTime, start, change, duration);                        
            element.scrollTop = position; 
            if (elapsedTime < duration) {
                timeOut = setTimeout(function() {
                    animateScroll(elapsedTime);
                }, increment);
            }
        };
    
        animateScroll(0);
    
        return stopAnimation
    
        function stopAnimation() {
            clearTimeout( timeOut )
        }
    }
    
    function easeInOut(currentTime, start, change, duration) {
        currentTime /= duration / 2;
        if (currentTime < 1) {
            return change / 2 * currentTime * currentTime + start;
        }
        currentTime -= 1;
        return -change / 2 * (currentTime * (currentTime - 2) - 1) + start;
    }
    
    0 讨论(0)
  • 2020-11-22 11:54

    Just made this javascript only solution below.

    Simple usage:

    EPPZScrollTo.scrollVerticalToElementById('wrapper', 0);
    

    Engine object (you can fiddle with filter, fps values):

    /**
     *
     * Created by Borbás Geri on 12/17/13
     * Copyright (c) 2013 eppz! development, LLC.
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
     * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     *
     */
    
    
    var EPPZScrollTo =
    {
        /**
         * Helpers.
         */
        documentVerticalScrollPosition: function()
        {
            if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
            if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
            if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
            return 0; // None of the above.
        },
    
        viewportHeight: function()
        { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },
    
        documentHeight: function()
        { return (document.height !== undefined) ? document.height : document.body.offsetHeight; },
    
        documentMaximumScrollPosition: function()
        { return this.documentHeight() - this.viewportHeight(); },
    
        elementVerticalClientPositionById: function(id)
        {
            var element = document.getElementById(id);
            var rectangle = element.getBoundingClientRect();
            return rectangle.top;
        },
    
        /**
         * Animation tick.
         */
        scrollVerticalTickToPosition: function(currentPosition, targetPosition)
        {
            var filter = 0.2;
            var fps = 60;
            var difference = parseFloat(targetPosition) - parseFloat(currentPosition);
    
            // Snap, then stop if arrived.
            var arrived = (Math.abs(difference) <= 0.5);
            if (arrived)
            {
                // Apply target.
                scrollTo(0.0, targetPosition);
                return;
            }
    
            // Filtered position.
            currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);
    
            // Apply target.
            scrollTo(0.0, Math.round(currentPosition));
    
            // Schedule next tick.
            setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
        },
    
        /**
         * For public use.
         *
         * @param id The id of the element to scroll to.
         * @param padding Top padding to apply above element.
         */
        scrollVerticalToElementById: function(id, padding)
        {
            var element = document.getElementById(id);
            if (element == null)
            {
                console.warn('Cannot find element with id \''+id+'\'.');
                return;
            }
    
            var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
            var currentPosition = this.documentVerticalScrollPosition();
    
            // Clamp.
            var maximumScrollPosition = this.documentMaximumScrollPosition();
            if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;
    
            // Start animation.
            this.scrollVerticalTickToPosition(currentPosition, targetPosition);
        }
    };
    
    0 讨论(0)
提交回复
热议问题