javascript獲取瀏覽器視口尺寸程式碼例項

螞蟻小編發表於2017-04-14

本章節介紹一下如何利用javascript獲取瀏覽器視口尺寸。

關於視口可以參閱什麼是瀏覽器視口介紹一章節。

程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  margin:0px;
  padding:0px;
}
body {
  background:#ccc;
}
#show {
  width:100px;
  height:50px;
  background:red;
  position:fixed;
  top:10px;
  left:10px;
}
</style>
<script type="text/javascript">
function getViewportSize(w){
  //使用指定視窗,如果不帶引數則使用當前視窗
  w = w || window;
     
  if(w.innerWidth != null)
    return { w: w.innerWidth, h: w.innerHeight };    
  var d = w.document;
  //標準模式
  if(document.compatMode == "CSS1Compat")
    return { w: d.documentElement.clientWidth,h: d.cocumentElement.clientHeight };
                  
  //怪異模式
  return { w: d.body.clientWidth, h: d.body.clientHeight }
}
window.onresize = function () {
  var size = getViewportSize();
  show.innerHTML = size.w + "<br/>" + size.h
}
</script>
</head>
<body>
<div id="show"></div>
</body>
</html>

調整一下視窗的大小即可檢視程式碼的功能,程式碼比較簡單更多內容可以參閱相關閱讀。

相關閱讀:

(1).innerWidth可以參閱window.innerWidth一章節。

(2).clientWidth可以參閱clientWidth一章節。

(4).onresize事件可以參閱javascript resize事件一章節。

相關文章