我想基于检测到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>
知道我对元标记代码做错了吗?
答案 0 :(得分: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');
}
}
答案 1 :(得分: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>
答案 2 :(得分: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" />';