javascript 特效实现(2)——回到顶部效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <title>回到顶部效果(原生js)</title>
    <style type="text/css">
        body{
            margin: 0;

        }
        .bg{
            width: 1022px;
            margin: 0 auto;
        }
        .btn{
            display: none;
            width: 75px;
            height: 75px;
            background:url(../images/网页top小图标(返回顶部)/返回顶部-085.png) no-repeat left top;
            position: fixed;
            left: 50%;
            margin-left: 530px;
            bottom: 10px;
            text-indent: -9999px;
            outline: none;
        }
        .btn:hover{
            background-position: 0 -75px;
        }
    </style>
    
    <script>        
    var timer=null;
    var isScroll=true;
    //1.2构造oScroll函数
    function oScroll(){
        var osTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1滚动高度,兼容
        var oSpeed=Math.ceil(osTop/4);//滚动速度
        document.documentElement.scrollTop=document.body.scrollTop=osTop-oSpeed;
        if(osTop==0){//判断到达顶部,清理定时器
            clearInterval(timer);
        }
        isScroll=true;    
    }
                        
    window.onload=function() {
        var obtn=document.getElementById('btn');//获取按钮元素
        var clientHeight=document.documentElement.clientHeight||document.body.clientHeight;

        // 1.点击返回按钮事件    
        btn.onclick=function(){//为按钮绑定点击事件
            timer=setInterval(oScroll,50);    
        }    
        window.onscroll=function() {
            var osTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1滚动高度,兼容
            if (osTop>clientHeight) {
                btn.style.display="block";
            }else{
                btn.style.display="none";
            }
            if(!isScroll){
                clearInterval(timer);
            }
            isScroll=false;
        }
    }    


    </script>

</head>
<body>
    <div class="bg">
        <img src="../images/jz.jpg">
    </div>
    <a href="javascript:void(0);" title="返回顶部" id="btn" class="btn">返回顶部</a>
</body>
</html>

 

转载于:https://www.cnblogs.com/web-HCJ/p/5513351.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值