答案 0 :(得分:1150)
@media (width)
和@media (height)
值var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.innerWidth
和.innerHeight
@media (width)
和@media (height)
initial-scale
并缩放variations可能导致移动设备值错误地缩小到PPK称之为visual viewport且小于@media
的值值undefined
- document.documentElement.clientWidth
和.clientHeight
@media (width)
和@media (height)
{li> same as jQuery(window).width()
jQuery 调用浏览器视口matchMedia
获取任意单位的精确尺寸答案 1 :(得分:106)
$(window).width()
和$(window).height()
答案 2 :(得分:69)
您可以使用window.innerWidth和window.innerHeight属性。
答案 3 :(得分:31)
如果你不使用jQuery,那就太难了。这是一个应该适用于所有新浏览器的代码段。 IE中的Quirks模式和标准模式的行为不同。这照顾它。
var elem = (document.compatMode === "CSS1Compat") ?
document.documentElement :
document.body;
var height = elem.clientHeight;
var width = elem.clientWidth;
答案 4 :(得分:11)
我知道这有一个可以接受的答案,但我遇到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);
答案 5 :(得分:11)
我能够在JavaScript中找到一个明确的答案:The Definitive Guide,第6版,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")
这一事实,一切看起来都不错。
答案 6 :(得分:10)
我看了一眼,发现了一种跨浏览器的方式:
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;
}
&#13;
<!DOCTYPE html>
<html>
<body onresize="myFunction()" onload="myFunction()">
<p>
Try to resize the page.
</p>
<p id="demo">
</p>
</body>
</html>
&#13;
答案 7 :(得分:9)
此代码来自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);
答案 8 :(得分:9)
window.innerHeight
和document.documentElement.clientHeight
之间存在差异。第一个包括水平滚动条的高度。
答案 9 :(得分:8)
如果您正在寻找能够在移动设备上以虚拟像素提供正确值的非jQuery解决方案 ,并且您认为普通window.innerHeight
或document.documentElement.clientHeight
可以解决您的问题,请先学习此链接:http://tripleodeon.com/wp-content/uploads/2011/12/table.html
开发人员已经做了很好的测试,揭示了问题:您可以获得Android / iOS,横向/纵向,普通/高密度显示器的意外值。
我目前的答案不是银弹(// todo),而是警告那些准备将任何给定解决方案从此线程快速复制粘贴到生产代码中的人。
我在移动设备上寻找虚拟像素中的页面宽度,我发现唯一正常工作的代码是(出乎意料!)window.outerWidth
。我稍后会检查这个表,以便在我有空的时候给出高度,不包括导航栏。
答案 10 :(得分:6)
符合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将是不可见的但会消耗一些空间,这将导致滚动条出现等。
答案 11 :(得分:3)
这就是我这样做的方式,我在IE 8中尝试过 - &gt; 10,FF 35,Chrome 40,它将在所有现代浏览器中非常流畅(如定义window.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)
);
}
答案 12 :(得分:1)
如果您使用的是React,则可以使用最新版本的react钩子。
// Usage
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
答案 13 :(得分:0)
您可以使用
window.addEventListener('resize' , yourfunction);
当窗口调整大小时,它将运行您的功能。
当您使用window.innerWidth
或document.documentElement.clientWidth
时,它是只读的。
您可以在函数中使用if语句并使其变得更好。
答案 14 :(得分:0)
您可以简单地使用 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>