0

我想根据对 android 或 iphone 的检测来更改元视口标签。我有这个代码,但它不工作:

<script type="text/javascript">
var metas = document.getElementsByTagName('meta');
var i;
var ua = navigator.userAgent;

var isAndroid = navigator.userAgent.match(/Android/i) !=null;
var isAndroid = /Android/i.test(ua);

var isiPhone = navigator.userAgent.match(/iPhone/i) !=null;
var isiPhone = /iPhone/i.test(ua);

if(isiPhone) {
for (i=0; i<metas.length; i++) {
  if (metas[i].name == "viewport") {
    metas[i].content = "";
  }
}
} else if(isAndroid) {
for (i=0; i<metas.length; i++) {
  if (metas[i].name == "viewport") {
    metas[i].content = "";
  }
}
} else {
for (i=0; i<metas.length; i++) {
  if (metas[i].name == "viewport") {
    metas[i].content = "width=device-width, initial-scale=.5";
  }
}
}
</script>

我尝试了这段代码作为测试,它工作得很好:

<script type="text/javascript">
var isiPad = navigator.userAgent.match(/iPad/i) != null;
var ua = navigator.userAgent;
var isiPad = /iPad/i.test(ua) || /iPhone OS 4_3_3/i.test(ua) || /iPhone OS 4_3_3/i.test(ua);

var isAndroid = navigator.userAgent.match(/Android/i) !=null;
var isAndroid = /Android/i.test(ua);

var isiPhone = navigator.userAgent.match(/iPhone/i) !=null;
var isiPhone = /iPhone/i.test(ua);

if(isiPad) {
alert("hello ipad!");
} else if(isAndroid) {
alert("hello android!");
} else if(isiPhone) {
alert("hello iphone!");
}
</script>

知道我在元标记代码上做错了什么吗?

4

3 回答 3

1

定位元视口并测试用户代理:

 viewport = document.querySelector("meta[name=viewport]");

 var iOS_iphone = ( navigator.userAgent.match(/(iPhone)/i) ? true : false );

    if (iOS_iphone==true){
        viewport.setAttribute('content', 'width=device-width, initial-scale=0.2, maximum-scale=0.2, user-scalable=no');
        }

    if( navigator.userAgent.match(/Android/i)){ 
        viewport.setAttribute('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0');
        }
    }
于 2012-12-07T14:11:38.807 回答
0

我使用了开源的Mobile Detect php 脚本。这是我下载轻量级脚本后所需的全部内容:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();
if ($detect->isMobile() && !$detect->isTablet())
    echo '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />';
于 2013-05-25T01:27:53.607 回答
0

我使用以下代码仅允许用户在 iPad 上进行缩放。它不依赖于 jQuery,因此可以出于性能原因放置在头部、视口元数据之后和任何其他外部脚本之前。

<!-- Allow zooming for iPad only -->
<script>
    if (navigator.userAgent.match(/iPad/i)) {
        var viewport = document.querySelector("meta[name=viewport]");
        viewport.setAttribute('content', 'width=device-width; initial-scale=1; user-scalable=1;');
    }
</script>
于 2013-01-07T20:14:22.420 回答