2011-04-18 17:22
iphone/ipad异常刚猛,在此把收集到的一些开发技巧罗列出来,方便项目中参考使用,如下: 侦测iPhone/iPod 开发特定设备的移动网站,首先要做的就是设备侦测了。下面是使用Javascript侦测iPhone/iPod的UA,然后转向到专属的URL。 if((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/iPod/i))){ if(document.cookie.indexOf("iphone_redirect=false")==-1){ window.location="http://m.example.com"; } } 虽然Javascript是可以在水果设备上运行的,但是用户还是可以禁用。它也会造成客户端刷新和额外的数据传输,所以下面是服务器端侦测和转向: if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone')|| strstr($_SERVER['HTTP_USER_AGENT'],'iPod')){ header('Location: http://yoursite.com/iphone'); exit(); } 设置viewpoint和屏幕等宽 如果不设置viewpoint,网站在viewpoint就会显示成缩略形式。如果你专门为iPhone/iPod开发网站,这一条很有用,而且很简单,只需要插入到head里就可以: <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> 使用iPhone规格图标 如果你的用户将你的网站添加到home screen,iPhone会使用网站的缩略图作为图标。然而你可以提供一个自己设计的图标,这样当然更好。图片是57×57大小,png格式。不需要自己做圆角和反光,系统会自动完成这些工作。然后将下面这条加入head中: <rel="apple-touch-icon" href="images/youricon.png"/> 阻止旋转屏幕时自动调整字体大小 -webkit-text-size-adjust是webkit的私有css: html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {-webkit-text-size-adjust:none;} 侦测设备旋转方向 iPhone可以在横屏状态下浏览网页,有时候你会想知道用户设备的手持状态来增强可用性和功能。下面一段Javascript可以判断出设备向哪个方向旋转,并且替换css: window.οnlοad=function initialLoad(){updateOrientation();} function updateOrientation(){ var contentType = “show_”; switch(window.orientation){ case0: contentType += “normal”; break; case-90: contentType += “right”; break; case90: contentType += “left”; break; case180: contentType += “flipped”; break; } document.getElementById(“page_wrapper”).setAttribute(“class”, contentType); } iPhone才识别的CSS 如果不想设备侦测,可以用CSS媒体查询来专为iPhone/iPod定义样式。 @media screen and (max-device-width: 480px) {} 缩小图片 网站的大图通常宽度都超过480像素,如果用前面的代码限制了缩放,这些图片在iPhone版显示显然会超过屏幕。好在iPhone机能还够,我们可以用CSS让iPhone自动将大图片缩小显示。 @media screen and (max-device-width: 480px){ img{max-width:100%;height:auto;} } 注意如果原图片非常大,或一个页面非常多图,最好还是在服务器端缩放到480像素宽,iPhone只需要在正常浏览时缩略到320像素。这样不会消耗太多流量和机能。 默认隐藏工具栏 iPhone的浏览器工具栏会在页面最顶端,卷动网页后才隐藏。这样在加载网页完成后显得很浪费空间,特别是横向屏幕时。我们可以让它自动卷动上去。 window.addEventListener('load',function(){ setTimeout(scrollTo,0,0,1); },false); 使用特殊链接 这两条不用说了吧: <a href="tel:12345654321">打电话给我</a> <a href="sms:12345654321">发短信</a> 模拟:hover伪类 因为iPhone并没有鼠标指针,所以没有hover事件。那么CSS :hover伪类就没用了。但是iPhone有Touch事件,onTouchStart 类似 onMouseOver,onTouchEnd 类似 onMouseOut。所以我们可以用它来模拟hover。使用Javascript: var myLinks = document.getElementsByTagName('a'); for(var i =0; i < myLinks.length; i++){ myLinks[i].addEventListener(’touchstart’,function(){this.className= “hover”;},false); myLinks[i].addEventListener(’touchend’,function(){this.className= “”;},false); } 然后用CSS增加hover效果: a:hover, a.hover{/* 你的hover效果 */} 这样设计一个链接,感觉可以更像按钮。并且,这个模拟可以用在任何元素上。 iphone fixed positioning 关于漂浮定位,测试后发现 { position: fixed; } 不能为其用, 参考资料: iPhone CSS—tips for building iPhone websites iPhone & iPod Detection Using Javascript iPhone Development: 12 Tips To Get You Started Tutorial: Building a website for the iPhone hover pseudoclass for the iPhone fixed-positioning-on-mobile-safari |