见代码(html)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <!--<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=2.0,user-scalable=1"/>--> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body onload= "bodyfinish()"> <div id="unit" style=" 320px; height:48px; position:relative;"> <p>mogoads</p> </div> </body> <script type="text/javascript"> function bodyfinish(){ var include = false; var metas = document.getElementsByTagName('meta'); var i; console.log("for begin"); for (i=0; i<metas.length; i++) { if (metas[i].name == "viewport") { include = true; metas[i].content = "width=device-width, minimum-scale=1.0, maximum-scale=2.0, user-scalable=1"; console.log("in for set meta"); break; } } if(!include){ console.log("set meta"); var head = document.getElementsByTagName('head')[0]; console.log("set meta after %s",head); var newElement = document.createElement('meta'); newElement.setAttribute('name', 'viewport'); newElement.setAttribute('content', 'width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=2.0,user-scalable=1'); head.appendChild(newElement); var s = document.getElementsByTagName('meta'); for(i=0;i<s.length; i++){ console.log("%d",i); if (s[i].name == "viewport") { var content_s = s[i].content; console.log("viewport have add"); } } } } </script> </html>
重点是这个javascript
var newElement = document.createElement('meta'); newElement.setAttribute('name', 'viewport'); newElement.setAttribute('content', 'width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=2.0,user-scalable=1'); head.appendChild(newElement);
关于meta 中参数的使用请参看
http://blog.caesarchi.com/2012/05/html-viewport-meta.html
http://www.w3.org/TR/css-device-adapt/#the-lsquomax-zoomrsquo-property