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

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


当前回答

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

其他回答

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"),一切看起来都很好。

符合W3C标准的解决方案是创建一个透明的div(例如使用JavaScript动态创建),将其宽度和高度设置为100vw/100vh (Viewport单位),然后获取其offsetWidth和offsetHeight。之后,可以再次删除该元素。这在较旧的浏览器中行不通,因为视口单元相对较新,但如果你不关心它们,而是关心(即将到来的)标准,你肯定可以这样做:

var objNode = document.createElement("div");
objNode.style.width  = "100vw";
objNode.style.height = "100vh";
document.body.appendChild(objNode);
var intViewportWidth  = objNode.offsetWidth;
var intViewportHeight = objNode.offsetHeight;
document.body.removeChild(objNode);

当然,你也可以设置objNode.style.position = "fixed",然后使用100%作为宽度/高度——这应该有同样的效果,并在一定程度上提高兼容性。另外,一般来说,将位置设置为固定可能是一个好主意,因为否则div将是不可见的,但会消耗一些空间,这将导致出现滚动条等。

此代码来自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);