Javascript 如果在Chrome、Firefox或Safari上未指定DOCTYPE,是否有办法找到视口';她身高多少?
下面的代码可以使用普通JavaScript或jQuery正确地找到视口的高度,但是如果未指定Javascript 如果在Chrome、Firefox或Safari上未指定DOCTYPE,是否有办法找到视口';她身高多少?,javascript,jquery,viewport,doctype,quirks-mode,Javascript,Jquery,Viewport,Doctype,Quirks Mode,下面的代码可以使用普通JavaScript或jQuery正确地找到视口的高度,但是如果未指定DOCTYPE,那么报告类似410的两行现在将报告类似3016的内容 如果未指定DOCTYPE,是否有办法找到视口的高度 <!DOCTYPE html> <html> <head> <style> body { height: 3000px; } </style> <script src="http://ajax.googlea
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
主体{高度:3000px;}
onload=函数(){
log(“jqueryversion”,$.fn.jQuery);
log(“document.compatMode为”,document.compatMode);
//使用jQuery
log(“$(window.height()为“,$(window.height());
//使用普通JavaScript
log(“document.documentElement.clientHeight is”,document.documentElement.clientHeight);
}
你好
获取视口高度:
console.log(window.innerHeight);
旁注:。在奇怪的页面上使用jQuery(没有指定doctype)可能会产生意外的结果。它没有在“怪癖”模式下进行测试,如果它出现故障,您将无法获得任何支持。我最近在开发bookmarklet时遇到了这个问题,我无法控制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;
或
我们都可以感谢Andy Langston,不管他是谁(;这里有一个通用的JS,它应该可以在大多数浏览器(FF、Cr、IE6+)中使用: 参考:
jQuery不支持怪癖模式。顺便说一句,
height:3000;
在非怪癖模式下无效。您的意思是3000px
?粗心的错误。立即更正
var h = viewport().height,
w = viewport().width;
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;
}