我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
当前回答
此代码来自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);
其他回答
您可以简单地使用JavaScript window.matchMedia()方法根据CSS媒体查询检测移动设备。这是检测移动设备的最佳和最可靠的方法。
下面的例子将告诉你这个方法是如何工作的:
<script>
$(document).ready(function(){
if(window.matchMedia("(max-width: 767px)").matches){
// The viewport is less than 768 pixels wide
alert("This is a mobile device.");
} else{
// The viewport is at least 768 pixels wide
alert("This is a tablet or desktop.");
}
});
</script>
应该是这样
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
你可以使用 窗口。addEventListener('resize',你的函数); 当窗口调整大小时,它将运行你的函数。 当你使用window的时候。innerWidth或document.documentElement.clientWidth它是只读的。 你可以在你的函数中使用if语句,使它更好。
跨浏览器@media (width)和@media (height)值
const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
窗口。innerWidth和window.innerHeight
获取包含滚动条的CSS viewport @media (width)和@media (height) initial-scale和缩放变化可能会导致移动值错误地缩小到PPK所称的可视视口,并且小于@media值 由于本机舍入,缩放可能导致值相差1px IE8-未定义
document.documentElement.clientWidth和.clientHeight
等于CSS视口宽度减去滚动条宽度 当没有滚动条时,匹配@media (width)和@media (height) 与jQuery(window).width()相同,jQuery调用浏览器视口 提供跨浏览器 如果缺少doctype则不准确
资源
各种维度的实时输出 Verge使用跨浏览器视口技术 实际使用matchMedia来获得任何单位的精确尺寸
窗户和窗户是有区别的。innerHeight和document.documentElement.clientHeight。第一个包括水平滚动条的高度。