JS實現快速回到頭部的方法

<html>javascript

    <head>
        <meta charset="UTF-8">
        <title>實現回到頂部</title>
    </head>
    <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>html

    <body style="height:1000px;">
        HELLO WORLD
        <div id="to_top">返回頂部</div>
    </body>java

</html>chrome

 

20180507更新,發現上面的這一串代碼不兼容IE,經修改,如下代碼在IE8測試可行。瀏覽器

<!DOCTYPE html>
<html>
<head>
    <title>兼容IE,chrome 等全部瀏覽器 回到頂部代碼</title>
        <meta charset="UTF-8">
 
</head>
<body>
    <div style="width: 980px; height: 1024px;">HELLO WORLD</div>
    <p id="to_top" style="border: 1px red solid;" onclick="goTopEx()">
        返回頂部
    </p>
    <SCRIPT type=text/javascript>  
    // JavaScript Document  
    function goTopEx(){  
            var obj=document.getElementById("to_top");  
            alert(obj)
            obj.onclick=function(){ 
                document.documentElement.scrollTop=1;  
                document.body.scrollTop=1;  
            }  
            return;    
    }  
    </SCRIPT>   
</body>
</html>測試

相關文章
相關標籤/搜索