2013-02-04 46 views
1

此代碼僅基於瀏覽器在加載時的大小,只是想知道我可以實現什麼,以獲得當前瀏覽器的大小和基於當前信息的工作。實時瀏覽器大小檢測

我已經嘗試將它包裝在resize()中,但它會導致它行爲異常,即切換持續開啓和關閉,或者在縮小的瀏覽器中加載時根本無法工作。

它是一個響應站點,其中頁腳菜單只是大屏幕上的靜態鏈接,但在小屏幕上變成了下拉菜單。

var myWidth = 0, myHeight = 0; 

    if(typeof(window.innerWidth) == 'number') { 
     //Non-IE 
     myWidth = window.innerWidth; 
     myHeight = window.innerHeight; 
    } else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { 
     //IE 6+ in 'standards compliant mode' 
     myWidth = document.documentElement.clientWidth; 
     myHeight = document.documentElement.clientHeight; 
    } 

    if(myWidth < 980) { 
     $("#footer h3").click(function() { 
       $(this).toggleClass("active"); 
       $(this).parent().find("ul").slideToggle('medium');  
     }); 
    } 

回答

1
var myWidth = 0, myHeight = 0; 


function getSize(){ 

    if(typeof(window.innerWidth) == 'number') { 
     //Non-IE 
     myWidth = window.innerWidth; 
     myHeight = window.innerHeight; 
    } else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { 
     //IE 6+ in 'standards compliant mode' 
     myWidth = document.documentElement.clientWidth; 
     myHeight = document.documentElement.clientHeight; 
    } 

} 

getSize(); // run first time 

$(window).resize(function(){ 
    getSize(); // do it on resize 
}); 


$("#footer h3").click(function() { 

     getSize(); // not needed but good to have 

     if(myWidth < 980) { 
      $(this).toggleClass("active"); 
      $(this).parent().find("ul").slideToggle('medium'); 
     } 

}); 
+1

謝謝,這個工作很好,我遇到了另一個問題,即使當我回到大屏幕時切換仍在進行,但我認爲我可以自己修復。 – Adrian

0

嘗試是這樣的:

var waitForFinalEvent = (function() { 
    var timers = {}; 
    return function (callback, ms, uniqueId) { 
     if (!uniqueId) uniqueId = "Don't call this twice"; 
     if (timers[uniqueId]) clearTimeout (timers[uniqueId]); 
     timers[uniqueId] = setTimeout(callback, ms); 
    }; 
})(); 

$(window).resize(function(){ 
    waitForFinalEvent(function(){ 
     // put all your code here 
    }, 20, "resize"); // replace 20 with every milliseconds to execute during 
         // resize 
}) 

你把代碼中有將執行每次調整窗口大小時,只需使用resize()並不總是可行的,因爲它並不一定檢查你正在調整大小。

1

您應該使用CSS媒體查詢來代替:

@media only screen and (max-device-width: 980px) { 
    // css goes here... 
} 

或包括條件樣式表:

<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="small-device.css" /> 

Here is a great article disusing responsive design

+0

還有...將這項工作在IE8?數百萬人仍然真的喜歡那個瀏覽器 –

+0

你需要使用類似http://code.google.com/p/css3-mediaqueries-js/的東西來讓IE8發揮出色 – keeg