gpt4 book ai didi

javascript - innerWidth 在手机上没有得到正确的宽度

转载 作者:行者123 更新时间:2023-11-29 21:32:34 27 4
gpt4 key购买 nike

我在下面有一段代码,它试图通过设备的 innerWidth 来确定某人是从移动设备还是台式机访问我的网站。但是,当我尝试从我的手机获取 innerWidth 时,它显示我的手机宽度是 980px?不过,我手机的宽度不可能接近那么宽。我手机的宽度在:300px左右,高度在500px左右。不过,在我的桌面上,它显示 1280px,这是正确的。我的问题是,为什么我的手机显示错误的宽度?除非有什么我没有正确理解的东西?

<?php
include("ajaxLink.php");
?>

<script>

$(function(){

var width = window.innerWidth;

alert(width);

if (width > 500) {
alert("going to index");
window.location = "/";
} //end of if (width > 500)
else {
alert("going to mobile");
window.location = "mobile.php";
} //end of else (width <= 500)

});

</script>

最佳答案

window.innerWidth 表示大多数移动设备上的视口(viewport) 像素,不是 物理像素。您应该能够通过巧妙地使用文档类型声明(例如..实际声明文档类型)以及在 head 部分中包含 meta viewport 标记来解决这个问题.这是来自 this article 的引述详细介绍了您的具体问题:

But when the viewport has not been constrained, and an HTML5 doctype (or none at all) is used, innerWidth will suddenly start to represent values much larger than the physical screen: and represent the width of the viewport canvas upon which the page has been rendered.

On a portrait iPhone, for example, the default viewport is 980 pixels. On a landscape iPhone it is, well, according to window.innerWidth, 981 (yes, really).

我会试试这个:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
</head>

根据 quirksmode , window.outerWidth 在缩放时也会从实际像素跳到视口(viewport)像素。

关于javascript - innerWidth 在手机上没有得到正确的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822517/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com