2011-02-13 67 views
9

我對JavaScript有點問題,爲了獲得我們使用screen.width的屏幕寬度,它返回整個屏幕分辨率,是否有一個命令來獲得瀏覽器可見部分的分辨率,如當瀏覽器沒有最大化?屏幕寬度vs可見部分

回答

28
function width(){ 
    return window.innerWidth 
     || document.documentElement.clientWidth 
     || document.body.clientWidth 
     || 0; 
} 

function height(){ 
    return window.innerHeight 
     || document.documentElement.clientHeight 
     || document.body.clientHeight 
     || 0; 
} 

使用它們返回height()或可視窗口width()

JSFiddle example.

+0

謝謝主席先生,window.innerWidth和window.innerHeight是我想要的東西,它只是工作!但爲什麼所有其他的代碼? – med 2011-02-13 22:30:49

0

你所描述的區域是視口,通常可以通過在現代瀏覽器中使用window.innerWidthwindow.innerHeight訪問。 IE6有點不同,但在this tutorial on obtaining viewport size中可以找到有關處理所有瀏覽器的視口寬度的更多信息。

1

我看到這個問題得到了回答,但這裏是我用一個圖像來說明的代碼。

function height(){ 
return(window.innerHeight)? 
window.innerHeight: 
document.documentElement.clientHeight||document.body.clientHeight||0; 
} 
$(document).ready(function(){ 
$('.first, .second').css('height',height()); 
}); 
$(window).resize(function() { 
$('.first, .second').css('height',height()); 
}); 

JSFiddle Example