window.innerHeight屬性和用法


是什么

innerHeight 和 innerWidth 都是window 的屬性,
表示文檔顯示區域的寬高,不包括工具欄等

怎么獲取

最新的瀏覽器都可以用window.innerHeight獲取

兼容性

這個屬性ie9+支持,其他的不支持
可以這樣獲取:
console.log(document.documentElement.clientHeight)
或者這樣:
console.log(document.body.clientHeight)
兩者區別:

  • 文檔中沒有文檔,那么document.body.clientHeight=0
  • document.body.clientHeight 顯示的是文檔中已有內容撐開的區域
  • window.innerHeight 和 ie的document.documentElement.clientHeight顯示的是文檔的區域
  • 就算里面沒有內容,也是顯示出應有的數值

與clientHeight的區別

  • window.innerHeight屬於BOM(瀏覽器對象模型),而document.documentElement.clientHeight屬於文檔對象模型
  • window.innerHeight獲取的高度包含橫向滾動條,而document.documentElement.clientHeight不包含橫向滾動條
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
		<style type="text/css">
			html,body{
				margin: 0;
				padding: 0;
				width: 100%;
				height: 100%;
			}
			div{
				width: 100%;
				height: 100%;
				background: lightblue;
			}
		</style>
	</head>
	<body>
		<div></div>
		<script type="text/javascript">
			console.log('innerHeight'+window.innerHeight);//innerHeight502
			console.log('clientHeight'+document.documentElement.clientHeight);//clientHeight502
		</script>
	</body>
</html>

此時打印結果:
innerHeight502
clientHeight502
當出現橫向的滾動條的時候,ocument.documentElement.clientHeight所獲得的高度就不包含滾動條的高度
此時打印結果:
innerHeight502
clientHeight485
可以看到document.documentElement.clientHeight的高度少了一些,原因就是document.documentElement.clientHeight不包括橫向滾動條


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM