[英]If DOCTYPE is not specified on Chrome, Firefox, or Safari, is there a way to find the viewport's height?
下面的代碼可以使用純JavaScript或jQuery正確找到視口的高度,但是如果未指定DOCTYPE
,那么兩條報告為410
現在將報告為3016
。
如果未指定DOCTYPE
是否可以找到視口的高度?
<!DOCTYPE html>
<html>
<head>
<style>
body { height: 3000px; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
onload = function() {
console.log("jQuery version", $.fn.jquery);
console.log("document.compatMode is", document.compatMode);
// using jQuery
console.log("$(window).height() is", $(window).height());
// using plain JavaScript
console.log("document.documentElement.clientHeight is", document.documentElement.clientHeight);
}
</script>
</head>
<body>
hi
這是一個通用JS,適用於大多數瀏覽器(FF,Cr,IE6 +):
var viewportHeight;
var viewportWidth;
if (document.compatMode === 'BackCompat') {
viewportHeight = document.body.clientHeight;
viewportWidth = document.body.clientWidth;
} else {
viewportHeight = document.documentElement.clientHeight;
viewportWidth = document.documentElement.clientWidth;
}
參考: 參考鏈接
獲取視口高度:
console.log(window.innerHeight);
經過古怪的Chrome和Firefox測試。
旁注: jQuery不支持quirks模式 。 在古怪的頁面上使用jQuery(未指定文檔類型)可能會產生意外結果。 它沒有在怪癖模式下進行測試,如果它破裂了,您將不會獲得任何支持。
我最近在開發一個無法控制DOCTYPE是否存在的書簽時遇到了這個問題。 最終,我發現這篇文章使我的生活變得如此輕松!
這是一個僅用於確定視口/窗口大小的簡單javascript函數:
function viewport(){
var e = window, a = 'inner';
if(!('innerWidth' in window)){
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[a+'Width'], height : e[a+'Height'] };
}
用法:
var vp = viewport(),
h = vp.height,
w = vp.width;
要么
var h = viewport().height,
w = viewport().width;
我們都可以感謝安迪·蘭斯頓(Andy Langston),無論他是誰(;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.