我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?

或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:


当前回答

你可以用窗户。innerWidth和window。innerHeight属性。

其他回答

你可以用窗户。innerWidth和window。innerHeight属性。

如果你不使用jQuery,它会变得很难看。下面是一个可以在所有新浏览器上运行的代码片段。在IE的Quirks模式和标准模式下,行为是不同的。这就搞定了。

var elem = (document.compatMode === "CSS1Compat") ? 
    document.documentElement :
    document.body;

var height = elem.clientHeight;
var width = elem.clientWidth;

您可以简单地使用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>

如果您正在寻找非jquery解决方案,在移动设备上给出正确的虚拟像素值,并且您认为普通窗口。innerHeight或document.documentElement.clientHeight可以解决您的问题,请先研究这个链接:https://tripleodeon.com/assets/2011/12/table.html

开发人员已经做了很好的测试,揭示了这个问题:你可能会在Android/iOS、横向/纵向、正常/高密度显示中得到意想不到的值。

我目前的答案还不是silver bullet (//todo),而是对那些打算从这个线程快速复制粘贴任何给定解决方案到生产代码的人的警告。

我在手机上寻找虚拟像素的页面宽度,我发现唯一的工作代码是window.outerWidth(出乎意料!)当我有时间的时候,我将检查这个表的正确解决方案,给出不包括导航栏的高度。

用于动态检测尺寸

你可以这样做在本地,没有Jquery或额外的

console.log('height默认值:'+window.visualViewport.height) console.log('width default:'+window.visualViewport.width) window.addEventListener(“调整”,(e) = > { console.log(' width: ${e.t target. visualviewport .width}px '); console.log(' height: ${e.t target. visualviewport .height}px '); });