我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口大小吗?
或者更好的是,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)
window.innerWidth
和window.innerHeight
@media (width)
,@media (height)
其中包括滚动条initial-scale
和缩放变化可能会导致移动值错误地缩小到 PPK 所谓的视觉视口并小于@media
值undefined
在 IE8-document.documentElement.clientWidth
和.clientHeight
@media (width)
并且@media (height)
当没有滚动条时jQuery(window).width()
浏览器视口相同 $(window).width()
和$(window).height()
您可以使用window.innerWidth和window.innerHeight属性。
如果您不使用 jQuery,它会变得丑陋。这是一个适用于所有新浏览器的代码段。IE 中 Quirks 模式和标准模式的行为不同。这会照顾它。
var elem = (document.compatMode === "CSS1Compat") ?
document.documentElement :
document.body;
var height = elem.clientHeight;
var width = elem.clientWidth;
我查看并找到了一种跨浏览器方式:
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>
我知道这是一个可以接受的答案,但我遇到了一个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")
,一切看起来都很好。
如果您正在寻找在移动设备上以虚拟像素提供正确值的非 jQuery 解决方案,并且您认为这很简单window.innerHeight
或document.documentElement.clientHeight
可以解决您的问题,请先研究此链接:https ://tripleodeon.com/assets/2011/12/表.html
开发人员进行了很好的测试来揭示问题:您可以获得 Android/iOS、横向/纵向、正常/高密度显示的意外值。
我目前的答案还不是灵丹妙药(//todo),而是对那些将要快速将任何给定解决方案从该线程复制粘贴到生产代码中的人的警告。
我在移动设备上寻找以虚拟像素为单位的页面宽度,我发现唯一的工作代码是 (unexpectedly!) 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>
);
}
您可以在 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`);
});
您可以使用
window.addEventListener('resize' , yourfunction);
它将在窗口调整大小时运行您的功能。当您使用window.innerWidth
或document.documentElement.clientWidth
它是只读的。您可以在您的函数中使用 if 语句并使其变得更好。
您可以简单地使用 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>
它应该是
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