1. 程式人生 > >js 文件寬高及視窗事件

js 文件寬高及視窗事件

可視區的尺寸

document.documentElement.clientWidth

document.documentElement.clientHeight

滾動距離

document.documentElement.scrollTop / scrollLeft

谷歌相容性處理 document.body.scrollTop

<!DOCTYPE html>
<html>
    <head>
        <meta charset="{CHARSET}">
        <title></title>
        <script>
            window.onload = function(){
                document.onclick = function(){
                    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;


                    alert(scrollTop);
                }
            }
        </script>
    </head>
    <body style="height: 2000px;">
    </body>
</html>

內容高度:

oDiv.scrollHeight / scrollWidth 除了邊框以外的寬高

<!DOCTYPE html>
<html>
    <head>
        <meta charset="{CHARSET}">
        <title></title>
        <script>
            window.onload = function(){
                document.onclick = function(){
                    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                    alert(document.getElementById('div1').scrollHeight);


                }
            }
        </script>
    </head>
    <body style="height: 2000px;">
        <div id="div1" style="width: 100px;height: 100px; border: 1px solid red;padding: 10px; margin: 10px;">
            <div style="width: 100px;height: 200px;background: blue;">
            </div>
        </div>
    </body>
</html>

文件高度:

document.documentElement.offsetHeight;

document.body.offsetHeight

ie下有相容性問題,效果同可視區寬高

 

onscroll:當滾動條滾動的時候觸發

onresize:當視窗大小發生改變的時候觸發

<!DOCTYPE html>
<html>
    <head>
        <meta charset="{CHARSET}">
        <title></title>
        <script>
            var i=0;
            window.onscroll = function(){
                document.title = i++;
            }

        </script>
    </head>
    <body style="height: 2000px;">
    </body>
</html>

window.onresize = function(){
       document.title = i++;
 }