我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口的大小吗?
或者更好的是,JavaScript浏览器的视口大小?见此处绿色区域:
当前回答
窗户和窗户是有区别的。innerHeight和document.documentElement.clientHeight。第一个包括水平滚动条的高度。
其他回答
符合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将是不可见的,但会消耗一些空间,这将导致出现滚动条等。
应该是这样
let vw = document.documentElement.clientWidth;
let vh = document.documentElement.clientHeight;
理解viewport: https://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts
上面链接的简写:viewport.moz.one
我已经建立了一个用于设备测试的网站:https://vp.moz.one
这是我做的方式,我在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)
);
}
jQuery维函数
$(window).width()和$(window).height()
跨浏览器@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来获得任何单位的精确尺寸