简体   繁体   English

为什么我的JavaScript无法检测到移动设备?

[英]why can't my javascript detect for mobile devices?

I'm using mdetect.js as obtained from mobileesp.com. 我使用mdetect.js从mobileesp.com获得。 The file looks perfect for what I need, and I've saved it locally. 该文件看起来很适合我的需要,并且已将其保存在本地。 Then on my HTML page, I want to call one of the functions and if it returns true (ie user is on mobile device) display a table at the top of the page saying our site doesn't support mobile devices currently. 然后,在我的HTML页面上,我想调用其中一个函数,如果该函数返回true(即用户在移动设备上),则在页面顶部显示一个表格,表明我们的网站当前不支持移动设备。 However, before even getting there I've already failed: 但是,在到达那里之前,我已经失败了:

<html>
<head>
<script type="text/javascript" src="mdetect.js"></script>
</head>
<body>
<h1>header 1</h1>
<script type="text/javascript">
document.write(DetectIphoneOrIpod());
</script>
<p>this is normal body text</p>
</body>
</html>

What am I doing wrong? 我究竟做错了什么? I haven't even gotten to the complicated stuff (for me at least). 我什至没有接触过复杂的东西(至少对我而言)。 Why won't it write true or false depending on what's returned from that function? 为什么不根据该函数返回的内容写true或false? Any help is appreciated. 任何帮助表示赞赏。

Thanks 谢谢

I don't know what the problem there is, but if you're using that entire file just for that function, it's overkill. 我不知道这是什么问题,但是如果您仅将整个文件用于该功能,那就太过分了。 Here's a trimmed down version which should also be easier to debug: 这是精简版,应该也更容易调试:

function isSmallIDevice() {
    return navigator.userAgent.search(/iPhone|iPod/i) > -1;
}

I think what you want to do is something like this: 我认为您想要做的是这样的:

<html>
<head>
<script type="text/javascript" src="mdetect.js"></script>
</head>
<body>
<h1>header 1</h1>
<script type="text/javascript">
    if (DetectIphoneOrIpod()) {
        document.write("<table>...</table>");
    }
</script>
<p>this is normal body text</p>
</body>
</html>

However, you probably want to use the DetectSmartphone() or DetectMobileQuick() functions to detect more mobile devices than just iPhones and iPod Touches. 但是,您可能想使用DetectSmartphone()DetectMobileQuick()函数来检测更多的移动设备,而不仅仅是iPhone和iPod Touch。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM