tid=159& 本帖最後由 media 於 2014-12-10 19:08 編輯
6 j# D2 T* s" j/ { j7 f# F# h, l3 c
& Z- o: T* x ~* o% F& M$ X最近用javascript取視窗的大小時,遇到不同瀏覽器無法偵測或不同的寬高的問題。後來找到下段這段程式碼,當用於點圖放大並顯示於前景中央位置時非常有用。
! ~0 H, y+ \& P! }1 y1 G/ l- <script type="text/javascript">3 b! @; H$ W3 `; I
- <!--
# Y" t9 U& r1 c3 ~/ C. }( E9 d - ) t5 K. m& T9 z1 b: W p1 \
- var viewportwidth;* G1 N# o1 ^5 S- M7 D; \
- var viewportheight;
2 q% |* c- h$ f$ Q6 y9 B! r& i - ! ]. n; h( E6 ~5 f5 b- Q
- // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight: f- B9 w3 p/ e
- " a1 A8 w3 _: z* T
- if (typeof window.innerWidth != 'undefined')" w4 i4 n+ ?9 }' Q! j
- {) B6 I& ~. y) o, @
- viewportwidth = window.innerWidth,
- g- x5 {6 Z- M6 w6 I - viewportheight = window.innerHeight
P1 j8 Y u+ i - }( e; \9 w5 H0 m' l0 }' x
-
# w* B* ?; ?3 Z8 L( x - // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
; {3 _$ c6 q5 T* r( o% x8 c. l
$ ~$ h, h: O7 i8 F- else if (typeof document.documentElement != 'undefined'
. r$ f- U0 F5 ?3 I& k - && typeof document.documentElement.clientWidth !=8 x9 A$ e5 S% y. w+ M
- 'undefined' && document.documentElement.clientWidth != 0)
# N2 Q8 ?! A9 w% b% o* W7 X - {' H5 h2 U5 v, l1 T9 H4 v( u$ b
- viewportwidth = document.documentElement.clientWidth,
5 O9 n7 u4 h/ a* m7 ?. ? - viewportheight = document.documentElement.clientHeight
9 l, e7 S5 t7 A6 j2 M' h - }
& P0 n8 U7 \1 d J% T, E' F K! b -
5 N* u m5 \- o4 g - // older versions of IE, {! M' G6 a- i/ K- u* S: C
-
& k& x3 a1 J# E" L3 U" \6 H - else# ~2 I, j' ~. G! S: Z% s! M
- {
* D; W+ D0 t g# k - viewportwidth = document.getElementsByTagName('body')[0].clientWidth,0 m+ J: t8 I9 g6 L( A
- viewportheight = document.getElementsByTagName('body')[0].clientHeight: @7 N5 ]) \; f6 f! J u; m
- }
: X2 a: A i0 E3 Z w - document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
! [$ I. y0 w G7 s# T- i - //--> ]1 r6 ]/ e0 W7 ^( x
- </script>
複製代碼 結果: 在google chrome 顯示結果
- ~/ V) y1 C9 q* z e) q5 `/ w
& d' Q- _, `: ?" H
- `, e+ R+ `0 Q& Q U0 a來源: Get viewport size (width and height) with javascript8 Q9 [4 z! q" T) f7 C
/ j9 F! H. ~- t0 t' h% }; e6 X* S
( A" S+ w& p; D, d5 @ |