2011-12-14 40 views
13

tôi đã sử dụng screen.width để có chiều rộng của trình duyệt. nó làm việc tốt với safari iPhone nhưng không làm việc trong điện thoại Android (nó cho thấy 800 chiều rộng cho trình duyệt Android).Javascript để phát hiện chiều rộng màn hình trình duyệt di động?

Có cách nào tương thích để có chiều rộng màn hình không. Tôi không muốn sử dụng UserAgent để kiểm tra xem trình duyệt trên thiết bị di động của mình. muốn sử dụng một javascript cho rằng và logic nên bao gồm chiều rộng màn hình.

Trả lời

3

Bạn có thể thử url này cho detect screen size and apply a CSS style

hoặc

<script type="text/javascript"> 

    function getWidth() 
    { 
    xWidth = null; 
    if(window.screen != null) 
     xWidth = window.screen.availWidth; 

    if(window.innerWidth != null) 
     xWidth = window.innerWidth; 

    if(document.body != null) 
     xWidth = document.body.clientWidth; 

    return xWidth; 
    } 
function getHeight() { 
    xHeight = null; 
    if(window.screen != null) 
    xHeight = window.screen.availHeight; 

    if(window.innerHeight != null) 
    xHeight = window.innerHeight; 

    if(document.body != null) 
    xHeight = document.body.clientHeight; 

    return xHeight; 
} 

</script> 


screen.height   shows the height of the screen 
screen.width   shows the width of the screen 
screen.availHeight shows height but removes the interface height like taskbar, and browser menu etc. 
screen.availWidth same as above,instead gives available width 
4

Nó biết vấn đề - xem here

Khi tải trang đầu tiên screen.widthscreen.height là sai. Hãy thử một thời gian chờ như thế này:

setTimeout(CheckResolution, 300); 

đâu CheckResolution là chức năng của bạn.

0

Tôi thấy rằng việc sử dụng window.outerWidth sẽ cung cấp giá trị chính xác. Thử nghiệm điều này bằng trình giả lập Android BrowserStack.

+0

này chỉ trả về chiều rộng của toàn bộ cửa sổ bao gồm cả chrome và tất cả mọi thứ. – malthoff

1

Đối với những người quan tâm đến việc giá trị chiều rộng của trình duyệt, tôi đã thử nghiệm một vài lựa chọn:

Tôi đang sử dụng bootstrap 3 và giải pháp duy nhất phù hợp với bootstrap 3 breakpoint với cả IE và Chrome được:

window.innerWidth 

Sau đây là các kết quả với 1200px cửa sổ với:

Chrome

$(window).width(): 1183 
$(document).width():1183 
screen.width: 1536 
$(window).innerWidth():1183 
$(document).innerWidth():1183 
window.innerWidth: 1200 
$(document).outerWidth():1183 
window.outerWidth: 1216 
document.documentElement.clientWidth: 1183 

Internet Explorer 10

$(window).width(): 1200 
$(document).width():1200 
screen.width: 1536 
$(window).innerWidth():1200 
$(document).innerWidth():1200 
window.innerWidth: 1200 
$(document).outerWidth():1200 
window.outerWidth: 1214 
document.documentElement.clientWidth: 1200 
Các vấn đề liên quan