tid=159& 本帖最後由 media 於 2014-12-10 19:08 編輯 / i0 ~( _6 O9 |: T. Y/ q& x
8 e, B/ c1 f D1 N
最近用javascript取視窗的大小時,遇到不同瀏覽器無法偵測或不同的寬高的問題。後來找到下段這段程式碼,當用於點圖放大並顯示於前景中央位置時非常有用。
& I! M& o0 Q D, E& n# K8 Z1 J3 |- <script type="text/javascript">" w7 z6 V7 e: [) t2 s" H
- <!--
9 [# U) q( ?9 ` - - q% C& D, r& T. V& W
- var viewportwidth;
8 z& I* s9 Z' A( l4 m! j: W - var viewportheight;' W8 k* x+ E+ U& i
- , K( @) @6 T# `
- // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight- G: z$ N9 p& L+ A) d. R
- 4 O4 D0 a6 h Z6 O9 r
- if (typeof window.innerWidth != 'undefined')+ V' K; Y7 r4 Q* w' A! C. z, W
- {+ N3 V U) v( E# m
- viewportwidth = window.innerWidth,; e+ I8 y0 T& J7 k2 h6 L0 B
- viewportheight = window.innerHeight1 o4 I, ?7 Z2 N$ b8 q9 z% P- ~
- }9 j* x l/ F, L3 @; H2 [
- 3 H. O a; s# R: F& _
- // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)/ @# J7 z1 B4 }- ], f( P0 ~
- i( A; ?! ^+ ~
- else if (typeof document.documentElement != 'undefined'
$ @1 b* J/ P3 i* ?/ I6 M - && typeof document.documentElement.clientWidth !=' g* c& U; ]: `0 m7 |
- 'undefined' && document.documentElement.clientWidth != 0)
' F8 R0 z$ Y& z. s# t% i - {) r6 T) U8 m6 a% C$ [8 N. o m& A
- viewportwidth = document.documentElement.clientWidth,+ J7 L3 _, H# \+ l" e
- viewportheight = document.documentElement.clientHeight
) w! T; |# Y; j4 e: h - }0 D/ G& _1 h2 C; t
-
) i# b8 }1 b i, O* C& z5 W5 J+ h - // older versions of IE
& L! Z( g9 L, I -
4 i" J5 I9 S5 B6 S6 \2 R& Y' Q - else
3 q% D) b6 f' h) H0 ~' e2 n8 g. v8 X - {, w0 j Y* c! `6 q* P3 T7 N/ z( E
- viewportwidth = document.getElementsByTagName('body')[0].clientWidth,2 }, {& B$ o. J+ c' l8 Q
- viewportheight = document.getElementsByTagName('body')[0].clientHeight
5 {* t8 V# G" q0 w. A - }
, v. C4 z) |% ~9 B' _ - document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');' Z% @' f2 ]4 a W; G1 ]0 ?8 f
- //-->
) s3 N: X3 o' e0 s4 x* x - </script>
複製代碼 結果: 在google chrome 顯示結果2 U5 G$ n& f5 U4 o
8 q1 c u. Z: f% X( Z6 o
1 N; m; V; ~) h# z3 Q$ S U9 B. L
來源: Get viewport size (width and height) with javascript
$ H+ }8 x/ ^& D% A
8 Z6 g- z9 W5 K! r( g& V
- k- E% p2 V( u, I- C; v o' Z |