Js、Jquery对goTop功能的实现

本文介绍用原生JS和Jquery分别实现的网页goTop按钮功能,以及在这个过程中碰到的问题。


最终实现的效果类似:http://sc2.163.com/home(注意右下角的top)


代码:

Jquery

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body{height: 2000px;}
        #goTop{
            display: none;
            cursor:pointer;
            background: url("common.png") no-repeat scroll 0 -460px;
            position: fixed;
            width: 60px;
            height: 60px;
            right: 20px;
            bottom: 20px;
            text-indent: -9999px;
            z-index: 100;
        }
        #goTop:hover{
            background-position: -100px -460px;
        }
    </style>
    <script src="../jQuery/jquery-1.11.3.js"></script>
    <script>
            $(function(){
                $(window).scroll(function(){
                    var scrH=document.documentElement.scrollTop+document.body.scrollTop;
                    if(scrH>200){
                        $('#goTop').fadeIn(400);
                    }else{
                        $('#goTop').stop().fadeOut(400);
                    }
                });
                $('#goTop').click(function(){
                    $('html,body').animate({scrollTop:'0px'},200);
                });
            });
    </script>
</head>
<body>
<a id="goTop" href="javascript:">返回顶层</a>
</body>
</html>

JS
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body{height: 2000px;}
        #goTop{
            display: none;
            cursor:pointer;
            background:url("common.png") no-repeat scroll 0 -460px;
            position: fixed;
            width: 60px;
            height: 60px;
            right: 20px;
            bottom: 20px;
            z-index: 100;
            text-indent: -9999px;
        }
        #goTop:hover{
            background-position: -100px -460px;
        }
    </style>
</head>
<body>
<a id="goTop" title="返回顶部" href="javascript:scroll(0,0)">返回顶层</a>
</body>
</html>
<script>
    (function() {
        function $(id){
            return document.getElementById(id);
        }
        window.οnscrοll=function(){
            var scrH=document.documentElement.scrollTop+document.body.scrollTop;
            if(scrH>200){
                $('goTop').style.display='block';
            }else{
                $('goTop').style.display='none';
            }
        };
    }());
</script>

代码好像没啥特别好解释了,说说我碰到的问题吧。

①在IE低版本下,不支持rgba属性~

②原生js的动画效果还不会实现,希望有人留言教下。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值