首頁  >  文章  >  web前端  >  Javascript實作取得視窗的大小與位置程式碼分享_javascript技巧

Javascript實作取得視窗的大小與位置程式碼分享_javascript技巧

WBOY
WBOY原創
2016-05-16 16:29:111371瀏覽

在Javascript中可以使用OuterWidth,OuterHeight 取得瀏覽器的大小.用 innerWidth,innerHeight 來取得視窗的大小(除去瀏覽器邊框部分)。對於IE6 及之前版本,要區分是標準模式,還是混雜模式。標準模式使用document.documentElement.clientWidth,document.documentElement.clientHeight;混雜模式使用document.body 的clientWidth,clientHeight。

複製程式碼 程式碼如下:

     (function () {
         var pageWidth = window.innerWidth;
         var pageHeight = window.innerHeight;
         var broswerWidth = window.outerWidth;
         var broswerHeight = window.outerHeight;
         alert(pageWidth " " pageHeight);
         alert(broswerWidth " " broswerHeight);
         if (typeof pageWidth != "number") {
             if (document.compatMode == "CSS1Compat") {  //The standard mode
                 pageWidth = document.documentElement.clientWidth;
                 pageHeight = document.documentElement.clientHeight;
             } else {
                 pageWidth = document.body.clientWidth;
                 pageHeight = document.body.clientHeight;
             }
         } 
     })();

取得視窗的位置:IE,chrome,Safari,使用screenLeft,screenTop 來取得視窗距離螢幕左邊和螢幕上邊的位置。而Firefox不支援此屬性,Firefox使用screenXP,screenY 達到相同的效果。

複製程式碼 程式碼如下:

    (function btnFun() {
        var leftPos = (typeof window.screenLeft == "number") ? window.screenLeft :
            window.screenX;
        var topPos = (typeof window.screenTop == "number") ? window.screenTop :
                         window.screenY;
        alert(leftPos " " topPos);
        //alert(window.screenLeft " " window.screenTop);
    })();
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn