tid=159& 本帖最後由 media 於 2014-12-10 19:08 編輯 / F2 `6 K) }$ g5 c# O% z5 @: @, |
( o$ P) v9 \& d0 |5 L& C5 v
最近用javascript取視窗的大小時,遇到不同瀏覽器無法偵測或不同的寬高的問題。後來找到下段這段程式碼,當用於點圖放大並顯示於前景中央位置時非常有用。
0 f" w) [! Q3 O( R. f- <script type="text/javascript">8 u. |7 b: s( d4 u
- <!--& S& U( ~0 ^9 d0 K* C! L
$ K7 M% l8 W' j% C0 g8 C- c! M* z% H- var viewportwidth;, y0 o% L \8 o( u1 ^) h" x6 r
- var viewportheight;$ P0 u' |' P |/ @4 J2 j0 T
-
8 W6 n0 i, s7 C. y* Y9 Q - // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
5 A1 s" X3 m, c) L* S( C -
( G" |+ ]6 P" G- `* ? - if (typeof window.innerWidth != 'undefined')
/ v2 }& t& D( A) c* y$ D - {* O* R6 q% `, t/ e, Y3 e
- viewportwidth = window.innerWidth,4 {6 T- f0 X( C6 E5 p. X+ B
- viewportheight = window.innerHeight
7 a; t* A5 z% L# R* q1 C3 X% ? - }
$ e4 {7 s$ y- W! E2 I -
1 R1 m1 R' p/ k0 D. Z - // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
1 U$ u" I' V! S5 B, l: L1 T5 l1 T - 6 y- F# V' S# D* s' i
- else if (typeof document.documentElement != 'undefined'% ~0 o2 [$ E- n+ H) \3 \7 b6 c
- && typeof document.documentElement.clientWidth !=, w1 r8 C i5 u5 l8 v
- 'undefined' && document.documentElement.clientWidth != 0)
R# X7 e+ l: E% |/ {: {) c. | - {* o2 ^: d+ _0 M6 ]' a+ G/ W
- viewportwidth = document.documentElement.clientWidth,
, h! ]" W, Z; C2 R1 L5 r6 k& f5 h - viewportheight = document.documentElement.clientHeight- @8 t0 G; m9 t
- }7 g* n7 \2 x2 p' I) }/ |% \
- r! a. @8 c! v5 P6 V6 o
- // older versions of IE
' x' z% b, y7 U6 L- Q' u8 Q6 E1 m4 R - 8 ?) r) E2 P, q, W6 l) C
- else* g! O8 P% r0 _* a$ v
- {* P9 u. e/ y3 C6 Y, D. k
- viewportwidth = document.getElementsByTagName('body')[0].clientWidth,* }/ }2 S! E8 Z: q
- viewportheight = document.getElementsByTagName('body')[0].clientHeight$ W% g, H: {/ T( \ h0 P* `
- }" V* A4 { p) t( ^% N( V0 q3 o# Y% B
- document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');, x3 D `' G& w# o" z( `4 d
- //-->
: l$ w, r8 q x1 `, g - </script>
複製代碼 結果: 在google chrome 顯示結果
8 b' i: W0 T2 f/ |- D# x
7 Y5 H0 X, s* G) a: L
8 h' B" e* }+ G& x# f
來源: Get viewport size (width and height) with javascript
$ W5 H, w/ F6 ?: s- |7 ]
' j& @4 Z9 B# r, d5 l- e' @8 t: |
|