如何使用javascript获取手机的宽度

问题描述 投票:1回答:4

所以我尝试使用jquery获取设备的宽度我为笔记本电脑和手机制作了2个界面的响应式网站,但问题是它在手机中无法工作,即使div测试的尺寸超出手机的尺寸请帮助我我用于重定向的代码在下面有注释

<html>
<head>
    <script src="./js/jquery-3.2.1.js"></script>
</head>
<body>
    <div id='test' style=" width: 2.54cm; height:2.54cm;"></div>
    //this div dimension works on laptop it measure exactly 2.54cm or 1nch
    //using ruler but in  mobiles it shrink and out of measure
    <script>
        //as you see I get the width of the div to get the pixel per inch
        var sqw=$('#test').width();
        var sqh=$('#test').height();
        //and I get the total width of the document
        var dheight=$(document).height();
        var dwidth=$(document).width();


    var w=dwidth/sqw;
    //and I divide the total width of the document to pixel per inch
    //the problem is the mobile show 10.98 inch where the mobile I use is 
    //miniFlare S5 cherrymobile with width of just 2.5 inches
    if(w<=7) {
        window.location.replace("./m_index.php");
    } else {
        window.location.replace("./d_index.php");
    }
</script>
</body>
</html>
javascript jquery html css
4个回答
3
投票

你正在使用jQuery。 From the docs .width() they say

此方法还能够找到窗口和文档的宽度。

// Returns width of browser viewport
$( window ).width(); // <- this is the one you are looking for!

// Returns width of HTML document
$( document ).width();

0
投票
var dwidth = window.innerWidth;
var dheight = window.innerHeight;

会做的


0
投票

您可以使用以下脚本获取跨平台:

const w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
const h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)

0
投票

请尝试以下代码,它可能满足您的要求<script> getScreensize(){ var sqw=$("body,html").width(); if(sqw<768){ //mobile screen logic } else{ //desktop screen logic } } $(window).resize(function(){ getScreensize(); }) </script>

© www.soinside.com 2019 - 2024. All rights reserved.