回到顶部功能实现

CSS上主要注意的是要把posiition设为fixed
JavaScript实现:

window.onload = function () {
    var button = document.getElementById("btn");
    var timer = null;

    var pagelookHeight = document.documentElement.clientHeight;
    window.onscroll = function () {
        var backtop = document.body.scrollTop || document.documentElement.scrollTop;
        if(backtop >= pagelookHeight){
            button.style.display = "";
        }else{
            button.style.display = "none";
        }
    }

    button.onclick = function () {
        timer = setInterval(function () {
            var backtop = Math.ceil(document.documentElement.scrollTop || document.body.scrollTop);
            console.log("backtop "+backtop);
            var speed = Math.ceil(backtop / 5);
            console.log("speed "+speed);
            if(document.documentElement.scrollTop){
                document.documentElement.scrollTop -= speed;
            }else{
                document.body.scrollTop -= speed;
            }
            if(backtop <= 0){
                clearInterval(timer);
            }
        },30);
    }
}

jQuery实现:
此效果来自:back-to-top
也可参考:

  • http://jsfiddle.net/gilbitron/Lt2wH/
jQuery(document).ready(function($){
    // browser window scroll (in pixels) after which the "back to top" link is shown
    var offset = 300,
        //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
        offset_opacity = 1200,
        //duration of the top scrolling animation (in ms)
        scroll_top_duration = 700,
        //grab the "back to top" link
        $back_to_top = $('.cd-top');

    //hide or show the "back to top" link
    $(window).scroll(function(){
        ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
        if( $(this).scrollTop() > offset_opacity ) { 
            $back_to_top.addClass('cd-fade-out');
        }
    });

    //smooth scroll to top
    $back_to_top.on('click', function(event){
        event.preventDefault();
        $('body,html').animate({
            scrollTop: 0 ,
            }, scroll_top_duration
        );
    });

});

你可能感兴趣的:(回到顶部功能实现)