本帖最後由 media 於 2014-12-10 19:08 編輯 7 v0 ]0 a. Y0 ~: B
, o5 V0 H; [( X. e最近用javascript取視窗的大小時,遇到不同瀏覽器無法偵測或不同的寬高的問題。後來找到下段這段程式碼,當用於點圖放大並顯示於前景中央位置時非常有用。
, |$ J$ L$ b& P2 p+ h- <script type="text/javascript">
# u- l. F* K% K k. R - <!--
9 O% z, n' b" ]5 m0 h2 A3 e
( r( \0 ~5 K% L- var viewportwidth;5 }6 @( C% t& w v5 w
- var viewportheight;2 @( B9 A9 n, z/ t' i( E& Z
-
; k; c2 R6 t6 ^+ p$ w+ t - // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
: G& Z. d1 i" ?) m -
5 o/ K7 m ]6 U1 f! a! t - if (typeof window.innerWidth != 'undefined')
! F8 p& b! k: S" L+ H - {
" u0 T% j9 k4 }6 d - viewportwidth = window.innerWidth,8 K7 u5 I2 t2 U$ g2 @" C8 A
- viewportheight = window.innerHeight
* j! H3 N9 w" m2 B0 i - }
M; T+ @8 J, w' i! n8 d+ ^3 c. B -
2 H$ u1 D) ]" H- I - // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
0 t' G \- g3 W& {, Q Z
# n \" x; Z% s J& L0 E3 g: H- else if (typeof document.documentElement != 'undefined'
2 {& H/ N; j, e' h- |& V( Z6 I* g - && typeof document.documentElement.clientWidth !=
/ |2 n' q. P7 {4 ]1 Z+ y% l3 [ - 'undefined' && document.documentElement.clientWidth != 0)
, Q) m6 ^: h- J - {9 N: j# J) @5 B6 A" F
- viewportwidth = document.documentElement.clientWidth,3 s$ j7 b1 |" }- i- j U/ N
- viewportheight = document.documentElement.clientHeight' `* b/ m. |- `: h( G' k6 C8 k9 c
- }+ I4 [; U( h* _9 q2 G
- 7 r' A7 l! z; s+ m( z, o
- // older versions of IE
% @: Z) W0 g7 n -
, I7 [* l4 V3 I( K) q- E+ V - else Z8 ?3 i* _% ?, W
- {& w1 g: i+ U; T
- viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
9 s. S/ ?* Z) y0 k ^7 g t - viewportheight = document.getElementsByTagName('body')[0].clientHeight
' v& s; j+ V; z- |; {6 @ - }
$ u5 _4 {' R7 b; v% o' a7 q - document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
7 L! L* `8 }" P/ T& A' q - //-->
% i: y- b+ |; j - </script>
複製代碼 結果: 在google chrome 顯示結果
9 o+ ~+ j) W( z/ L2 a
) ]" n* q" \ ~9 H. Z v/ u
5 V; T: L# q7 a. g" D1 j
來源: Get viewport size (width and height) with javascript
+ ]5 x6 k9 A* r' z6 i7 o7 ^ ?& S# g4 K& V
6 g; u; y! @( t1 K+ v0 P
|
|