Why isn't window.innerWidth returning the right value?

use*_*044 5 html javascript viewport width

I am trying to solve the problem of using Javascript to determine the width of my browser's "window". I'm aware different people can mean different things in this context so to be specific I mean the area in green as in this post.

I've read the first two replies to that post and a number of other stackoverflow solutions to this problem, none of which I could get to work: I am using Firefox 27.0.1 with the window maximised on a monitor that is 1920 pixels wide. The scripts says my viewport is 1536 pixels wide. I expected 1920 (or something close).

Based on what I have seen, it seemed to me the simplest solution in my case was this code:

<html>
<head>
<script type="text/javascript">
function onAfterLoad() {
    document.write('<p>Your viewport width is '+window.innerWidth+'</p>');
}
</script>
</head>
<body onload="onAfterLoad();">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在编写此代码时,请点击此处。这也说明我的视口宽度为 1536 像素,而我认为它应该是 1920 像素。

请问我哪里错了?

小智 7

检查您的视口元标记。它应该是:

<meta name="viewport" content="width=device-width,initial-scale=1" />


Gre*_*ndy 7

对我来说,这个问题是浏览器缩放的结果。尝试控制+滚轮,看看这是否会改变你得到的结果。如果是这样,请参阅如何在所有现代浏览器中检测页面缩放级别?


Vir*_*hah 6

我认为你应该尝试使用jQuery 维度函数。而是处理 Javascript 函数。

最基础的是

$(window).width()(获取浏览器的宽度)

$(window).height()(获取浏览器的高度)

希望这可以帮助。