tid=159& 本帖最後由 media 於 2014-12-10 19:08 編輯 % n" _. [3 r4 a$ M% f5 t
) U) w1 f/ |5 X: D4 B
最近用javascript取視窗的大小時,遇到不同瀏覽器無法偵測或不同的寬高的問題。後來找到下段這段程式碼,當用於點圖放大並顯示於前景中央位置時非常有用。, j2 C ]$ V) _" c) f/ ?/ n
- <script type="text/javascript">- L1 w: Q2 Z2 B# k% D
- <!--& s# k- o7 r% M7 d* `& O" n2 t/ M
6 f. d* g9 N1 h4 U' ]- var viewportwidth;5 c9 W) X( J+ J& F
- var viewportheight;) u2 c+ B- `2 }3 S( c( B( V
-
% l9 y9 z: v3 R7 d" N - // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
% h- t5 `* l9 B0 g1 \9 _/ K - $ s, A& b; N( @5 a) n
- if (typeof window.innerWidth != 'undefined')8 U5 C, y+ ]/ x D/ _3 ^: g: ]1 [
- {/ [; J4 g4 S( d Y1 ?6 O4 A
- viewportwidth = window.innerWidth," P5 C$ ?: Y0 i" @: N# W
- viewportheight = window.innerHeight* B! q! ?" N5 j5 ?% }; M2 S' D
- }+ u0 S5 C& X9 ?$ w( S+ s' m( B
-
1 E. G3 s& V0 n# k" \1 F - // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
( `* }+ v0 C5 R - / x2 z$ O+ L. x3 y4 ~, Q2 w7 z M/ b
- else if (typeof document.documentElement != 'undefined'
) S5 Z9 F L) O& _1 n& s$ n - && typeof document.documentElement.clientWidth !=% x- l. p4 ~: }
- 'undefined' && document.documentElement.clientWidth != 0)1 N4 |8 C0 o" K) F" Z
- {
2 m7 G" Z: h2 [; g - viewportwidth = document.documentElement.clientWidth,
# [1 n2 K2 B/ V - viewportheight = document.documentElement.clientHeight
* {/ ]) {& W2 H. |+ Q+ e - }
2 @2 H$ L/ _) l+ t# _. o% y - 4 @0 W+ s( r; ~& _: `$ Z9 n& ~1 J7 M
- // older versions of IE' U& d0 {+ ^6 X/ z
-
$ |/ U1 x# L, e/ ?% V' v A - else
# `1 O5 t* u" j( K5 N# V6 C% Y; }: s! U - {
, a% g% A% [: @% ?- L* e+ l, y) y - viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
) @8 b% I! M; [/ {7 W - viewportheight = document.getElementsByTagName('body')[0].clientHeight
6 D: k6 [/ }% M1 b z7 Q3 n; `1 [ - }# H* J m7 N4 R' w+ [ D' z
- document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
6 B% P, H! A7 ~1 y7 G: {+ d - //-->
# O& a* _, B7 q e" O* e( i3 U% M% z - </script>
複製代碼 結果: 在google chrome 顯示結果
' a. K5 c: x1 A- O) H7 z5 b
( E" @7 Z& b3 X8 \* U
5 k( R2 M0 _" ~
來源: Get viewport size (width and height) with javascript+ h) A/ C* E( a G
/ K% t B, J# o9 j! N& Y% s& Z
) J: ~0 l t6 D( t* @+ S
|