1. 程式人生 > >BOM應用(open、close、scrollTop)

BOM應用(open、close、scrollTop)

 開啟、關閉視窗:

  • open
<body>
<input type="button" value="開啟視窗" onclick="window.open('http://www.baidu.com')"/>
</body>

document.write:先清空然後再寫。

<body>
<input type="button" value="write" onclick="document.write('abc')"/><!--一點選按鈕 按鈕消失 abc出現-->
</body>

點選按鈕,執行程式碼:

 <script>
        window.onload=function(){
            var oTxt=document.getElementById('txt1');
            var oBtn=document.getElementById('btn1');

            oBtn.onclick=function(){
                var oNewWin=window.open('about:blank','_blank');
                oNewWin.document.write(oTxt.value);
               // document.write()--window.document.write()
            }
        }
    </script>
</head>
<body>
<textarea id="txt1" cols="30" rows="10"></textarea> <br/>
<input type="button" value="執行" id="btn1"/>
</body>
  • close

     火狐中,close只能關閉open開啟的視窗。

 <script>
        alert(window.navigator.userAgent);//當前瀏覽器版本資訊
        alert(window.location)//當前頁面的地址
 </script>

如果open給self的話就是location.

<body>
<input type="button" value="aaa" onclick="window.location='http://www.zhinengshe.com/';"/>
</body>

尺寸及座標:

<script>
        document.onclick=function(){
//IE、火狐相容
            alert(document.documentElement.scrollTop);
//chrome
            alert(document.body.scrollTop);
        }
</script>

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

 scrollTop的相容:

<script>
        document.onclick=function(){
            var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
            alert(scrollTop);
        }
</script>

右下角懸浮框:IE6不認fixed。

 <style>
        #div1{
            width: 100px;
            height: 200px;
            background: red;
            position: absolute;
            right: 0;
            bottom: 0;
        }
        body{
            height: 2000px;
        }

    </style>
    <script>
        //經常重新定位,所以會抖。
        window.onscroll=function(){
            var oDiv=document.getElementById('div1');
            var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
            oDiv.style.top=document.documentElement.clientHeight-oDiv.offsetHeight+scrollTop+'px';

        }
    </script>
</head>
<body>
<div id="div1"></div>

</body>

但是當改變可視區的大小時,懸浮框一開始不會隨著變化,那是因為沒有重新定位。

 <script>
        //經常重新定位,所以會抖。
        window.onscroll=window.onresize=function(){//window.onresize可視區大小移動時,重新定位
            var oDiv=document.getElementById('div1');
            var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
            oDiv.style.top=document.documentElement.clientHeight-oDiv.offsetHeight+scrollTop+'px';

        }
    </script>

解決抖動的問題:

userAgent>IE6        fixed

IE6                          運動