我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
当前回答
你可以用窗户。innerWidth和window。innerHeight属性。
其他回答
jQuery维函数
$(window).width()和$(window).height()
窗户和窗户是有区别的。innerHeight和document.documentElement.clientHeight。第一个包括水平滚动条的高度。
应该是这样
let vw = document.documentElement.clientWidth;
let vh = document.documentElement.clientHeight;
理解viewport: https://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts
上面链接的简写:viewport.moz.one
我已经建立了一个用于设备测试的网站:https://vp.moz.one
如果你不使用jQuery,它会变得很难看。下面是一个可以在所有新浏览器上运行的代码片段。在IE的Quirks模式和标准模式下,行为是不同的。这就搞定了。
var elem = (document.compatMode === "CSS1Compat") ?
document.documentElement :
document.body;
var height = elem.clientHeight;
var width = elem.clientWidth;
此代码来自http://andylangton.co.uk/articles/javascript/get-viewport-size-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' ] };
}
注意:要读取宽度,使用console.log('viewport width'+viewport().width);