js返回顶部事件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
<style>
    div{cursor:default;width:20px;height:80px;line-height:20px;border:1px solid black;position:fixed;right:0;bottom:20px;text-align:center;display:none;}
</style>
    </head>
    <body style="height:5000px">
        <div>
            返回顶部
        </div>
    </body>
<script>
    function css(obj, attr, val) {
    if (arguments.length == 3) { // 修改
        if (obj.currentStyle && attr == 'opacity') { // 如果返回的不是undefined(转换为false)就是IE浏览器
            obj.style.filter = 'alpha(opacity:' + val + ')';
        } else if (attr == 'opacity') {
            obj.style[attr] = val / 100;
        } else {
            //obj.style[attr] = val + 'px';
            obj.style[attr] = val;
        }
    } else if (arguments.length == 2) { // 获取
        if (obj.currentStyle) {
            if (attr == 'opacity') {
                return parseInt(obj.currentStyle.filter.split(':'));
            } else {
                return parseInt(obj.currentStyle[attr]);
            }
        } else {
            if (attr == 'opacity') {
                return parseInt(Math.round(getComputedStyle(obj, null)[attr] * 100));
            } else {
                var value = parseInt(getComputedStyle(obj, null)[attr]);
                return value;
            }
        }
    }
}



    for (var i=0;i<300;i++){
        document.write('Line ' + (i + 1) + '<br/>');
    }
    var oDiv = document.getElementsByTagName('div')[0];
    document.body.onscroll = function(){
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (scrollTop > 600){
            css(oDiv, 'display', 'block');
        }else{
            css(oDiv, 'display', 'none');
        }
    };

    oDiv.onclick = function(){
        // 没有动画效果
//      document.documentElement.scrollTop = 0;
//      document.body.scrollTop = 0;
        clearInterval(oDiv.timeHandler);
        oDiv.timeHandler = setInterval(function(){
            var cur = scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

            if (cur != 0){
                var speed = (0 - cur) / 10;
                speed = speed>0?Math.ceil(speed):Math.floor(speed);
                document.documentElement.scrollTop = cur + speed;
                document.body.scrollTop = cur + speed;
            }else{
                console.log(11);
                clearInterval(oDiv.timeHandler);        
            }
        }, 30);
    };
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值