js 回到顶部(兼容ie)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>无标题文档</title>
    <style>
        body{margin:0; padding:0}
        #to_top{width:30px; height:40px; padding:20px; font:14px/20px arial; text-align:center;  background:#06c; position:absolute; cursor:pointer; color:#fff}
    </style>
    <script>
        window.onload = function(){
            var oTop = document.getElementById("to_top");
            var screenw = document.documentElement.clientWidth || document.body.clientWidth;
            var screenh = document.documentElement.clientHeight || document.body.clientHeight;
            oTop.style.left = screenw - oTop.offsetWidth +"px";
            oTop.style.top = screenh - oTop.offsetHeight + "px";
            window.onscroll = function(){
                var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
                oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px";
            }
            oTop.onclick = function(){
                document.documentElement.scrollTop = document.body.scrollTop =0;
            }
        }

    </script>
</head>

<body style="height:1000px;">

<h1>返回顶部</h1>


<div id="to_top">返回顶部</div>
</body>
</html>

转载自:http://www.cnblogs.com/jingangel/archive/2012/03/08/2385939.html


当页面特别长的时候,用户想回到页面顶部,必须得滚动好几次滚动键才能回到顶部,如果在页面右下角有个“返回顶部”的按钮,用户点击一下,就可以回到顶部,对于用户来说,是一个比较好的体验。

实现原理:当页面加载的时候,把元素定位到页面的右下角,当页面滚动时,元素一直位于右下角,当用户点击的时候,页面回到顶部。

要点一:document.documentElement.clientWidth || document.body.clientWidth; 获得可视区的宽度。后面是兼容chrome,前面是兼容其它浏览器。

要点二:oTop.style.left = screenw - oTop.offsetWidth +"px";  当页面加载时,让元素的位置位于页面最右边,用可视区的宽度减去元素本身的宽度。

要点三:oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px"; 当页面滚动时,元素的Y坐标位置等于可视区的高度减去元素本身的高度,加上滚动距离。

要点四:document.documentElement.scrollTop = document.body.scrollTop =0; 当点击元素时,让页面的滚动距离为0.写两个是为了兼容。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值