我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
当前回答
用于动态检测尺寸
你可以这样做在本地,没有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 '); });
其他回答
用于动态检测尺寸
你可以这样做在本地,没有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 '); });
这是我做的方式,我在IE 8 -> 10, FF 35, Chrome 40中尝试过,它将在所有现代浏览器(作为窗口)中工作得非常流畅。innerWidth是定义的),在IE 8(没有window.innerWidth),它工作顺利,任何问题(如闪烁,因为溢出:“隐藏”),请报告它。我不是真的对视口高度感兴趣,因为我做这个函数只是为了解决一些响应工具,但它可能会被实现。希望它能有所帮助,我感谢评论和建议。
function viewportWidth () {
if (window.innerWidth) return window.innerWidth;
var
doc = document,
html = doc && doc.documentElement,
body = doc && (doc.body || doc.getElementsByTagName("body")[0]),
getWidth = function (elm) {
if (!elm) return 0;
var setOverflow = function (style, value) {
var oldValue = style.overflow;
style.overflow = value;
return oldValue || "";
}, style = elm.style, oldValue = setOverflow(style, "hidden"), width = elm.clientWidth || 0;
setOverflow(style, oldValue);
return width;
};
return Math.max(
getWidth(html),
getWidth(body)
);
}
窗户和窗户是有区别的。innerHeight和document.documentElement.clientHeight。第一个包括水平滚动条的高度。
我找到了一个跨浏览器的方法:
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>
此代码来自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);