这是整个代码:
<html> <head> <title>WP8 Test</title> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <style type="text/css"> @-webkit-viewport{width:device-width} @-moz-viewport{width:device-width} @-ms-viewport{width:device-width} @-o-viewport{width:device-width} @viewport{width:device-width} @media screen and (min-width: 1024px) { body { background-color: red; } } @media screen and (min-width: 768px) and (max-width: 1024px) { body { background-color: blue; } } @media screen and (min-width: 480px) and (max-width: 768px) { body { background-color: green; } } @media screen and (max-width: 480px) { body { background-color: yellow; } } </style> <script type="text/javascript"> if (navigator.userAgent.match(/IEMobile\/7\.0/)) { var msViewportStyle = document.createElement("style"); msViewportStyle.appendChild( document.createTextNode( "@-ms-viewport{width:auto!important}" ) ); document.getElementsByTagName("head")[0]. appendChild(msViewportStyle); } </script> </head> <body> text </body> </html>
正如您所看到的,它非常简单,有4个不同的“断点”,其中主体的背景颜色将根据不同的屏幕宽度而变化.在我的WP8设备(Lumia 822)上注意到它在IE中不起作用后,我开始在Google上搜索问题,这似乎是一个众所周知的问题.所以我找到并尝试过的解决方案来自这里:
http://timkadlec.com/2013/01/windows-phone-8-and-device-width/
这似乎很简单,因为我将五行添加到我的CSS顶部:
@-webkit-viewport{width:device-width} @-moz-viewport{width:device-width} @-ms-viewport{width:device-width} @-o-viewport{width:device-width} @viewport{width:device-width}
然后添加一些JS来检测来自UA的IE Mobile浏览器.我有两个问题:
首先 – 当我提醒我的用户代理字符串时,我从我的WP8设备获得以下内容:
Mozilla/4.0 (compatible; MSIE 7.0;Windows Phone OS 7.0; Trident/3.1;IEMobile/7.0;NOKIA; Lumia 822
根据上面的文章和this article,它应该是IEMobile / 10.0.关于为什么我的不同的任何想法?这似乎是Windows Phone 7用户代理字符串.为什么我的WP8设备会显示出来?
由于存在这种差异,我不得不将JS更改为匹配7.0而不是10,否则将永远不会满足if条件.
所以,即使如此,使用上面的代码,没有任何反应,我的屏幕在我的WP8设备上加载白色.谁能看到我做错了什么?
更新:
似乎JS抛出了一个错误:
Unexpected call to method or property access
所以我找到了解决方案,here:
if (navigator.userAgent.match(/IEMobile\/7\.0/)) { var s = document.createElement("style"); s.setAttribute('type','text/css'); var cssText = "@-ms-viewport{width:auto!important}"; if(s.styleSheet) { // IE does it this way s.styleSheet.cssText = cssText } else { // everyone else does it this way s.appendChild(document.createTextNode(cssText)); } document.getElementsByTagName("head")[0].appendChild(s); }
但是,即使现在代码执行成功,我的媒体查询仍然被忽略,我仍然看到白页加载.有任何想法吗?
更新2:
我发现了另一篇文章,here(滚动到底部),说明了GDR3更新(我通过开发程序):
Great news! Microsoft have fixed the viewport issue in WP8 Update 3
(GDR3).Using device-width in a CSS @-ms-viewport rule now correctly renders
pages at the device-width,instead of the resolution width.
所以,我再次尝试删除Javascript,并将此添加到我的CSS顶部:
@-ms-viewport{ width:device-width }
但同样,没有CSS加载.
更新3:
看来我的用户代理可能是正确的.当我在WP8设备上导航到whatsmyuseragent.com时,它会显示正确的UA.也许它与它是一个本地IIS 8.0网站有关,当它报告不正确的一个?如果是这样的话,我无法从Windows Phone本地测试我的网站?有没有人这样做过?