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

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


当前回答

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

其他回答

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

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

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

如果你正在使用React,那么在最新版本的React钩子中,你可以使用这个。

// Usage
function App() {
   const size = useWindowSize();

   return (
     <div>
       {size.width}px / {size.height}px
     </div>
   );
 }

https://usehooks.com/useWindowSize/

我找到了一个跨浏览器的方法:

function myFunction(){ if(window.innerWidth !== undefined && window.innerHeight !== undefined) { var w = window.innerWidth; var h = window.innerHeight; } else { var w = document.documentElement.clientWidth; var h = document.documentElement.clientHeight; } var txt = "Page size: width=" + w + ", height=" + h; document.getElementById("demo").innerHTML = txt; } <!DOCTYPE html> <html> <body onresize="myFunction()" onload="myFunction()"> <p> Try to resize the page. </p> <p id="demo"> &nbsp; </p> </body> </html>