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

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


当前回答

窗户和窗户是有区别的。innerHeight和document.documentElement.clientHeight。第一个包括水平滚动条的高度。

其他回答

窗户和窗户是有区别的。innerHeight和document.documentElement.clientHeight。第一个包括水平滚动条的高度。

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

$(window).width()和$(window).height()

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

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

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

我在O'Reilly的《JavaScript: The definitive Guide》第6版中找到了一个明确的答案,第391页:

这个解决方案即使在Quirks模式下也能工作,而ryanve和ScottEvernden目前的解决方案则不能。

function getViewportSize(w) {

    // Use the specified window or the current window if no argument
    w = w || window;

    // This works for all browsers except IE8 and before
    if (w.innerWidth != null) return { w: w.innerWidth, h: w.innerHeight };

    // For IE (or any browser) in Standards mode
    var d = w.document;
    if (document.compatMode == "CSS1Compat")
        return { w: d.documentElement.clientWidth,
           h: d.documentElement.clientHeight };

    // For browsers in Quirks mode
    return { w: d.body.clientWidth, h: d.body.clientHeight };

}

除了我想知道为什么行if (document.compatMode == "CSS1Compat")不是if (d.compatMode == "CSS1Compat"),一切看起来都很好。