打造行動 Web App 時,往往有許多細節需要特別處理,才能讓網頁在 iOS 等平台上擁有接近原生 App 的體驗。以下彙整 15 個實用小技巧,從主畫面圖示到全螢幕、狀態欄與各種手勢控制,一網打盡。
<!-- 57*57 -->
<link rel="apple-touch-icon" href="touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="touch-icon-iphone4.png" />
<link rel="apple-touch-icon" sizes="144x144" href="touch-icon-ipad-retina.png" />
透過 apple-touch-icon 並搭配 sizes 屬性,即可為不同裝置與解析度提供專屬圖示。
<!-- iPhone -->
<link href="apple-touch-startup-image-320x460.png" media="(device-width: 320px)" rel="apple-touch-startup-image" />
<!-- iPhone (Retina) -->
<link href="apple-touch-startup-image-640x920.png" media="(device-width: 320px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />
<!-- iPad (直向) -->
<link href="apple-touch-startup-image-768x1004.png" media="(device-width: 768px) and (orientation: portrait)" rel="apple-touch-startup-image" />
<!-- iPad (橫向) -->
<link href="apple-touch-startup-image-748x1024.png" media="(device-width: 768px) and (orientation: landscape)" rel="apple-touch-startup-image" />
利用 media 查詢針對不同裝置與方向,指定對應的啟動圖。
讓 Web App 隱藏瀏覽器介面、更像原生 App:
<meta name="apple-mobile-web-app-capable" content="yes" />
content 屬性可設為 default、black 或 black-translucent:
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="viewport" content="user-scalable=no, width=device-width" />
<script>
function BlockMove(event) {
// 告訴 Safari 不要移動視窗
event.preventDefault();
}
</script>
<body ontouchmove="BlockMove(event);">
...
</body>
先判斷裝置是否支援 orientationchange 事件,若不支援則退回使用 resize:
// 偵測是否支援 orientationchange,否則退回 resize 事件
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent, function() {
alert('螢幕旋轉了:' + window.orientation);
}, false);
// 全螢幕獨立模式下的 Mobile Safari
if (("standalone" in window.navigator) && window.navigator.standalone) {
var noddy, remotes = false;
document.addEventListener('click', function(event) {
noddy = event.target;
// 向上冒泡直到命中連結或最上層的 HTML 元素
while (noddy.nodeName !== "A" && noddy.nodeName !== "HTML") {
noddy = noddy.parentNode;
}
if ('href' in noddy && noddy.href.indexOf('http') !== -1 &&
(noddy.href.indexOf(document.location.host) !== -1 || remotes)) {
event.preventDefault();
document.location.href = noddy.href;
}
}, false);
}
<meta name="format-detection" content="telephone=no" />
-webkit-text-size-adjust: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
<input type="text" x-webkit-speech />
<input type="file" accept="image/*; capture=camera" />
<input type="file" accept="video/*; capture=camcorder" />
<input type="file" accept="audio/*; capture=microphone" />
<a href="sms:18888886666,18888885555">傳送簡訊給多人</a>
<a href="sms:18888886666?body=hello">傳送帶內容的簡訊</a>
<a href="tel:18888886666">撥打電話 18888886666</a>
掌握這些技巧,就能讓你的行動 Web App 在使用者眼中更貼近原生應用的操作感受。