回到顶部功能实现

来源:互联网 发布:阿拉伯血钻野燕麦知乎 编辑:程序博客网 时间:2024/04/30 19:32

CSS上主要注意的是要把posiition设为fixed

无动画的回到顶部功能,使用简单的a标签就行

<a href="#" class="top">↑</a>

jquery实现主要使用了scrollTop()方法,而且要注意兼容性:

<a href="javascript:;" class="top">↑</a>

jquery事件如下:

    $(function () {        //滚动事件        $(window).scroll(function () {            var top = $(this).scrollTop();            if(top>200){                $('.top').stop().fadeIn();            }else{                $('.top').stop().fadeOut();            }        })        //点击事件        $('.top').click(function () {            //body不支持ie,firefox,使用html            $('body,html').stop().animate({scrollTop:0},300);        })    })

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        );    });});
0 0
原创粉丝点击