我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口大小吗?
或者更好的是,JavaScript 浏览器的视口大小?在此处查看绿色区域:
https://i.stack.imgur.com/zYrB7.jpg
html
标记getComputedStyle
。
跨浏览器@media(宽度)和@media(高度)值
const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
window.innerWidth 和 window.innerHeight
获取包含滚动条的 CSS 视口 @media (width) 和 @media (height)
初始缩放和缩放变化可能会导致移动值错误地缩小到 PPK 所称的视觉视口并小于 @media 值
由于本机舍入,缩放可能会导致值偏离 1px
在 IE8 中未定义-
document.documentElement.clientWidth 和 .clientHeight
等于 CSS 视口宽度减去滚动条宽度
当没有滚动条时匹配@media(宽度)和@media(高度)
与jQuery调用浏览器视口的jQuery(window).width()相同
可用的跨浏览器
如果缺少 doctype,则不准确
资源
各种维度的实时输出
边缘使用跨浏览器视口技术
实际使用 matchMedia 来获得任何单位的精确尺寸
$(window).width()
和 $(window).height()
$(window).height();
返回 536,而 $("html").height();
返回 10599
您可以使用 window.innerWidth 和 window.innerHeight 属性。
https://developer.mozilla.org/@api/deki/files/213/=FirefoxInnerVsOuterWidth2.png
document.documentElement.clientWidth
比 window.innerWidth
更准确,支持更广泛
document.documentElement.clientWidth
为我提供视口宽度,而 window.innerWidth 为我提供文档宽度。是的,就是这样。
如果您不使用 jQuery,它会变得丑陋。这是一个适用于所有新浏览器的代码段。 IE 中 Quirks 模式和标准模式的行为不同。这会照顾它。
var elem = (document.compatMode === "CSS1Compat") ?
document.documentElement :
document.body;
var height = elem.clientHeight;
var width = elem.clientWidth;
document.documentElement
元素上使用 clientHeight
,它将为您提供视口大小。要获得文档大小,您需要执行 document.body.clientHeight
。正如 Chetan 所解释的,这种行为适用于现代浏览器。这很容易测试。只需打开一个控制台并在几个打开的选项卡上键入 document.documentElement.clientHeight
。
我查看并找到了一种跨浏览器方式:
函数 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 = "页面大小:width=" + w + ", height=" + h; document.getElementById("demo").innerHTML = txt; }
尝试调整页面大小。
我知道这是一个可以接受的答案,但我遇到了 clientWidth
不起作用的情况,因为 iPhone(至少我的)返回 980,而不是 320,所以我使用了 window.screen.width
。我在现有网站上工作,变得“响应式”,需要强制更大的浏览器使用不同的元视口。
希望这对某人有所帮助,它可能并不完美,但它适用于我在 iOs 和 Android 上的测试。
//sweet hack to set meta viewport for desktop sites squeezing down to mobile that are big and have a fixed width
//first see if they have window.screen.width avail
(function() {
if (window.screen.width)
{
var setViewport = {
//smaller devices
phone: 'width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no',
//bigger ones, be sure to set width to the needed and likely hardcoded width of your site at large breakpoints
other: 'width=1045,user-scalable=yes',
//current browser width
widthDevice: window.screen.width,
//your css breakpoint for mobile, etc. non-mobile first
widthMin: 560,
//add the tag based on above vars and environment
setMeta: function () {
var params = (this.widthDevice <= this.widthMin) ? this.phone : this.other;
var head = document.getElementsByTagName("head")[0];
var viewport = document.createElement('meta');
viewport.setAttribute('name','viewport');
viewport.setAttribute('content',params);
head.appendChild(viewport);
}
}
//call it
setViewport.setMeta();
}
}).call(this);
我能够在 JavaScript: The Definitive Guide, 6th Edition by O'Reilly, p. 中找到明确的答案。 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")
之外,一切看起来都不错。
documentElement.clientWidth
不会响应 iOS 上的设备方向更改。 b)显示物理像素数(实际上没用)而不是虚拟像素
如果您正在寻找非 jQuery 解决方案在移动设备上提供正确的虚拟像素值,并且您认为普通的 window.innerHeight
或 document.documentElement.clientHeight
可以解决您的问题,请先研究此链接:{ 1}
开发人员进行了很好的测试来揭示问题:您可以获得 Android/iOS、横向/纵向、正常/高密度显示的意外值。
我目前的答案还不是灵丹妙药(//todo),而是对那些将要快速将任何给定解决方案从该线程复制粘贴到生产代码中的人的警告。
我在移动设备上寻找以 虚拟像素 为单位的页面宽度,我发现唯一有效的代码是(出乎意料!)window.outerWidth
。当我有时间时,我稍后将检查此表以获取给出高度(不包括导航栏)的正确解决方案。
此代码来自 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);
window.innerHeight
和 document.documentElement.clientHeight
之间存在差异。第一个包括水平滚动条的高度。
符合 W3C 标准的解决方案是创建一个透明 div(例如使用 JavaScript 动态),将其宽度和高度设置为 100vw/100vh(视口单位),然后获取其 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 将不可见但会占用一些空间,这将导致出现滚动条等。
这就是我这样做的方式,我在 IE 8 -> 10、FF 35、Chrome 40 中尝试过,它在所有现代浏览器(定义为 window.innerWidth)和 IE 8(没有 window.innerWidth)中都非常流畅。 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)
);
}
如果您使用的是 React,那么使用最新版本的 react hooks,您可以使用它。
// Usage
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
https://usehooks.com/useWindowSize/
您可以简单地使用 JavaScript window.matchMedia() 方法来检测基于 CSS 媒体查询的移动设备。这是检测移动设备的最佳和最可靠的方法。
以下示例将向您展示此方法的实际工作原理:
<script>
$(document).ready(function(){
if(window.matchMedia("(max-width: 767px)").matches){
// The viewport is less than 768 pixels wide
alert("This is a mobile device.");
} else{
// The viewport is at least 768 pixels wide
alert("This is a tablet or desktop.");
}
});
</script>
用于动态检测大小
您可以在 Native 中完成,无需 Jquery 或附加功能
console.log('height default :'+window.visualViewport.height) console.log('width default :'+window.visualViewport.width) window.addEventListener('resize',(e)=>{ console.log( `width: ${e.target.visualViewport.width}px`); console.log(`height: ${e.target.visualViewport.height}px`); });
它应该是
let vw = document.documentElement.clientWidth;
let vh = document.documentElement.clientHeight;
了解视口:https://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts
以上链接的简写:viewport.moz.one
我建立了一个用于在设备上进行测试的网站:https://vp.moz.one
您可以使用 window.addEventListener('resize' , yourfunction);
它会在窗口调整大小时运行您的函数。当您使用 window.innerWidth
或 document.documentElement.clientWidth
时,它是只读的。您可以在您的函数中使用 if 语句并使其变得更好。
不定期副业成功案例分享
$
替换为verge
。如果您想集成到 jQuery 中,请执行jQuery.extend(verge)
。请参阅:verge.airve.com/#static<!DOCTYPE html>
才能使代码正常工作。document.documentElement.clientHeight
返回页面高度,而window.innerHeight
返回视口高度。巨大差距。