我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
当前回答
跨浏览器@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来获得任何单位的精确尺寸
其他回答
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;
如果你正在使用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"> </p> </body> </html>
用于动态检测尺寸
你可以这样做在本地,没有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 '); });