经常在做移动手机网站的时候由于需要在微信平台推广我们不得不去兼容他。在IOS上由于苹果把控的很好,浏览器内核都是统一的。所以自然没有兼容问题。但是安卓就不同了,碎片化的缘故。加上微信的WEBVIEW是定制过的浏览器,导致和原生的效果不同。下面是一个兼容方案。
首先你要设置meta viewport属性
<meta name="viewport" content="width=device-width, target-densityDpi=device-dpi, user-scalable=yes">
然后再JS代码中设置如下代码
var viewport = document.querySelector("meta[name=viewport]"); var winWidths=$(window).width(); var densityDpi=640/winWidths; densityDpi= densityDpi>1?300*640*densityDpi/640:densityDpi; if(isWeixin()){ viewport.setAttribute('content', 'width=640, target-densityDpi='+densityDpi); }else{ viewport.setAttribute('content', 'width=640, user-scalable=no'); window.setTimeout(function(){ viewport.setAttribute('content', 'width=640, user-scalable=yes'); },1000); } function isWeixin(){ var ua = navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i)=="micromessenger") { return true; } else { return false; } }
以下是判断浏览器类型后,通过js设置meta viewport属性的实例,在不同设备终端兼容性显示自适应页面
//获取并判断客户端类型 function iswhichwapdev(){ var viewport = document.querySelector("meta[name=viewport]");//获取meta对象的第一种方法 <code class="html spaces"></code><code class="html plain"> //var viewport = document.getElementsByTagName('meta')[1]; </code>//获取meta对象的第二种方法 var agentcheck=navigator.userAgent.toLowerCase(); var isAndroid=true; var isIPone=false; var keywords = ["mobile", "android", "symbianos", "windows phone", "mqqbrowser", "nokia", "samsung", "midp-2", "untrusted/1.0", "windows ce", "blackberry","ucweb", "brew", "j2me", "yulong", "coolpad", "tianyu", "ty-", "k-touch", "haier", "dopod", "lenovo", "huaqin", "aigo-", "ctc/1.0", "ctc/2.0", "cmcc", "daxian", "mot-", "sonyericsson", "gionee", "htc", "zte", "huawei", "webos", "gobrowser", "iemobile", "wap2.0","wapi","ipad","ipod"]; //判断是否是iphone; var rekeywords=["iphone"]; if (agentcheck!=null){ for (var i = 0; i < rekeywords.length; i++) { if ( agentcheck.indexOf(rekeywords[i].toLowerCase())>-1){ isAndroid=false; isIPone=true; } } } if (isAndroid){ for (var i = 0; i < keywords.length; i++) { if ( agentcheck.indexOf(keywords[i].toLowerCase())>-1) { viewport.setAttribute('content', 'width=772px,target-densitydpi=device-dpi, initial-scale=1.0, minimum-scale=1.0, maximum-scale=2.0, user-scalable=yes'); } } } if (isIPone) { viewport.setAttribute('content', 'width=772px,target-densitydpi=device-dpi, initial-scale=0.4, minimum-scale=0.4, maximum-scale=2.0, user-scalable=yes'); } }
快拿起安卓手机试试吧!
-END-