做手機版網頁時,真正卡住開發者的往往不是版面好不好看,而是「行動瀏覽器的行為和桌面差太多」:沒有真正的視窗寬度概念、沒有滑鼠、沒有 hover、鍵盤會蓋掉半個畫面。這份整理把常見需求拆成十一個主題,每一項都附上可直接複製的片段。
桌面瀏覽器的 viewport 是扣掉工具列、狀態列、捲軸之後真正能看網頁的區域。手機不同:多數行動瀏覽器在沒有任何宣告時,會假設頁面寬度約 980px 並整體縮小呈現,於是文字小到看不清。要拿回控制權,靠的是一行 meta。
可以操作的屬性有六個:
width // viewport 寬度(可為 200 ~ 10000,預設 980) height // viewport 高度(可為 223 ~ 10000) initial-scale // 初始縮放比例(大於 0,可到 10) minimum-scale // 允許縮放到的最小比例 maximum-scale // 允許縮放到的最大比例 user-scalable // 使用者能否手動縮放(yes / no)
寫法如下:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta id="viewport" name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- 讓網頁加到主畫面後以全螢幕 app 姿態開啟 -->
<meta name="apple-mobile-web-app-capable" content="yes">
<!-- 全螢幕時狀態列的樣式 -->
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- 不要把看起來像電話號碼的數字自動變成撥号链接 -->
<meta name="format-detection" content="telephone=no">
把 initial-scale 設為 1 之後,我們終於能以接近 1:1 的比例設計。這裡有個關鍵認知:iPhone 的 Safari 實際上從一開始就把整頁完整配置好,然後用 viewport 去「看」其中一部分;你手指拖動時,拖的其實是 viewport 而不是頁面。也正因如此,它沒有捲軸——不是隱藏,而是這個概念在行動裝置上並不存在,交互事件也跟桌面完全不同。
順帶一提,user-scalable=no 與 maximum-scale=1 會讓低視能使用者無法放大頁面,多數無障礙規範(WCAG 1.4.4)視此為妨礙。除非有全螢幕遊戲、地圖這類特殊需求,建議保留縮放能力。
<link rel="apple-touch-startup-image" href="startup.png"> <!-- 啟動畫面 -->
<link rel="apple-touch-icon" href="icon.png"> <!-- 書籤/主畫面圖示 -->
<!-- 依方向載入不同樣式表 -->
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
<!-- 也可以在 style 標籤上用 media 屬性 -->
<style media="all and (orientation:portrait)" type="text/css">
#landscape { display: none; }
</style>
<style media="all and (orientation:landscape)" type="text/css">
#portrait { display: none; }
</style>
手機沒有滑鼠,取而代之的是一組觸控事件:
// 手指相關 touchstart // 手指接觸螢幕 touchmove // 接觸後開始移動 touchend // 手指離開 touchcancel // 被系統中斷(來電、通知等) // 多指手勢 gesturestart // 兩指接觸螢幕 gesturechange // 兩指開始移動(縮放、旋轉) gestureend
事件物件上有三組清單與一組座標:
touches // 目前螢幕上所有手指 targetTouches // 落在目前目標元素上的手指 changedTouches // 本次事件中有變動的手指 clientX / clientY // 相對於 viewport(不含捲動) screenX / screenY // 相對於實體螢幕 pageX / pageY // 相對於整份文件(含捲動) target // 事件發生的節點 identifier // 該手指的唯一編號,多指時用來追蹤
多指操作一定要靠 identifier 追蹤,不能只用陣列索引,因為手指離開後索引會往前補位。
function orientationChange() {
switch (window.orientation) {
case 0:
alert("肖像模式 0, screen-width: " + screen.width + "; screen-height: " + screen.height);
break;
case -90:
alert("左旋 -90, screen-width: " + screen.width + "; screen-height: " + screen.height);
break;
case 90:
alert("右旋 90, screen-width: " + screen.width + "; screen-height: " + screen.height);
break;
case 180:
alert("倒置 180, screen-width: " + screen.width + "; screen-height: " + screen.height);
break;
}
}
addEventListener('load', function () {
orientationChange();
window.onorientationchange = orientationChange;
});
注意 window.orientation 現已標記為 deprecated,新專案建議改用 matchMedia("(orientation: ...)") 或 resize 搭配寬高比較。
addEventListener('load', function () {
// 頁面載入後把視窗往下捲 1px,網址列就會收起來
setTimeout(function () { window.scrollTo(0, 1); }, 100);
});
這招在舊版 iOS Safari 很有效,但現代瀏覽器多已改為工具列自動收放,scrollTo(0,1) 反而可能讓頁面一進來就微微下移。建議只做為漸進增強,並搭配 window.innerHeight 變化來重算高度相依的元素。
addEventListener('load', function () {
window.onmousewheel = twoFingerScroll;
}, false); // false:在冒泡階段呼叫;true 則在捕捉階段
function twoFingerScroll(ev) {
var delta = ev.wheelDelta / 120; // 正負代表方向,可據此執行對應操作
return true;
}
function isAppleMobile() {
return (navigator.platform.indexOf('iPad') != -1);
}
更通用的寫法是查 navigator.userAgent;但 UA 可被偽造,只能當作「介面微調」的依據,不能當作安全判斷。
var v = localStorage.getItem('n') ? localStorage.getItem('n') : ""; // 讀(不存在則給空字串)
localStorage.setItem('n', v); // 寫
localStorage.removeItem('n'); // 刪
名稱(key)記得用引號包成字串。另外要留意: Safari 在無痕模式下的 quota 為 0,setItem 會直接丟出例外,因此建議包在 try/catch 裡,並避免把敏感資料明文存入。
<a href="tel:12345654321">打電話給我</a> <a href="sms:12345654321">發短信</a> <!-- 也可以掛在非 a 標籤上 --> <td onclick="location.href='tel:122'">
<input type="text" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false">
帳號、密碼、序號、折扣碼這類欄位尤其需要關掉,否則使用者會被系統「貼心」地改成首字母大寫而輸入失敗。行動 Safari 另外支援 autocomplete="username"、autocomplete="one-time-code" 等語意值,能讓密碼管理器正確辨識欄位。
以下依 CSS 規範的分類整理常見的 -webkit- 私有屬性,方便對照查詢。
-webkit-border-radius: radius; // 圓角 -webkit-border-bottom-left-radius: radius; -webkit-border-top-left-radius: h_radius v_radius; -webkit-box-sizing: border-box | content-box; // 盒模型計算方式 -webkit-box-shadow: h-offset v-offset blur color; // 陰影 -webkit-margin-bottom-collapse: collapse | discard | separate; -webkit-margin-start / -webkit-padding-start: width; -webkit-border-image: url(borderimg.gif) 25 25 25 25 round; -webkit-appearance: push-button;
direction: rtl; unicode-bidi: bidi-override | embed | normal;
clip: rect(10px, 5px, 10px, 5px);
resize: auto | both | horizontal | none | vertical;
visibility: collapse | hidden | visible;
-webkit-transition: opacity 1s linear; // ease / linear / ease-in / ease-out / ease-in-out
-webkit-backface-visibility: visible | hidden;
-webkit-box-reflect: below 4px -webkit-gradient(linear, left top, left bottom,
from(transparent), color-stop(0.5, transparent), to(white));
-webkit-mask-image: -webkit-gradient(...); // 遮罩
-webkit-mask-attachment: fixed | scroll;
-webkit-perspective: value;
-webkit-perspective-origin: left top;
-webkit-transform: rotate(5deg);
-webkit-transform-style: flat | preserve-3d; // 2D 與 3D
text-shadow: #00FFFC 10px 10px 5px; text-transform: capitalize | lowercase | none | uppercase; word-wrap: break-word | normal; -webkit-text-fill-color: #ff6600; -webkit-text-size-adjust: none; // 防止轉屏時字體被縮放 -webkit-text-stroke: 15px #fff; -webkit-line-break: after-white-space | normal; -webkit-user-select: text | auto | none; -webkit-marquee: right large infinite normal 10s; -webkit-marquee-direction / -increment / -speed / -style;
-webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; -webkit-column-count: 3; // 分欄 -webkit-column-rule: 1px solid #fff; // solid / dashed / dotted / double / groove / ridge / inset / outset / none / hidden -webkit-column-break-after / -before: always | auto | avoid | left | right; -webkit-column-break-inside: avoid | auto;
-webkit-box-align: baseline | center | end | start | stretch; -webkit-box-direction: normal | reverse; -webkit-box-orient: block-axis | horizontal | inline-axis | vertical; -webkit-box-pack: center | end | justify | start; -webkit-tap-highlight-color: 顏色; // 點擊時的高亮色
Webkit 早期最具代表性的能力是「用 transition/animation 函式定義動畫」。keyframes 讓我們描述一段 0% 到 100% 的變化過程,之後重複呼叫即可:
@-webkit-keyframes DivZoom {
0% { -webkit-transform: scale(0.01) } /* 起點極小,但不能為 0 */
60% { -webkit-transform: scale(1.05) } /* 衝過頭一點 */
80% { -webkit-transform: scale(0.95) } /* 反彈 */
100% { -webkit-transform: scale(1.00) } /* 回到正常大小 */
}
.sZoom { -webkit-animation: DivZoom 0.5s ease-in-out; }
這正是當年 iPhone 跳出提示方塊那種「彈一下」的手感:0.5 秒、慢到快再到慢、預設播放一次。
animation 的組成屬性:
-webkit-animation-name: myKeyframes; // 對應 @keyframes 的名稱 -webkit-animation-duration: 3s; -webkit-animation-timing-function: ease; // linear / ease-in / ease-out / ease-in-out / cubic-bezier -webkit-animation-delay: 10ms; // 預設 0 -webkit-animation-iteration-count: 1; // infinite 為無限迴圈 -webkit-animation-direction: normal; // alternate 則奇偶次反向播放
transform 的四類操作:
scale(num, num) // 放大倍率,可拆成 scaleX / scaleY rotate(*deg) // 旋轉角度,可拆成 rotateX / rotateY skew(*deg) // 傾斜角度,可拆成 skewX / skewY translate(*, *) // 位移,可拆成 translateX / translateY
啟動動畫時有個眉角:元素播完一次動畫後,若樣式完全沒變,第二次套用同一個 class 不會重播。原範例的解法是用動畫延遲時間製造「變化」:
function pHelp() {
layerH.style.visibility = 'visible';
layerH.style.cssText = "-webkit-animation-delay: " + Math.random() + "ms";
layerH.className = 'sZoom';
}
用 Math.random() 產生 0 到 1 之間的隨機數,延遲不到一毫秒,使用者察覺不到,卻足以讓瀏覽器認為樣式有變動。今天更乾淨的做法是移除 class、強制重排、再加回:
el.classList.remove('sZoom');
void el.offsetWidth; // 強制 reflow
el.classList.add('sZoom');
/* 1. 鎖定 viewport:任何螢幕操作都不移動畫面(彈出鍵盤除外) */
ontouchmove="event.preventDefault()"
/* 2. 自訂點擊高亮色 */
-webkit-tap-highlight-color: rgba(0,0,0,0);
/* 3. 阻止轉屏時自動縮放字體 */
html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {
-webkit-text-size-adjust: none;
}
/* 4. 只針對 iPhone/iPod 的媒體查詢 */
@media screen and (max-device-width: 480px) {}
/* 5. 讓過寬的圖片自動縮進螢幕 */
@media screen and (max-device-width: 480px) {
img { max-width: 100%; height: auto; }
}
裝置偵測也可以在伺服器端做,避免客戶端轉址造成的額外往返:
if (strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod')) {
header('Location: https://yoursite.com/iphone');
exit();
}
不過更推薦的做法是「同一份 HTML、用響應式版面因應不同尺寸」,而不是維護兩套站體。
iPhone 沒有滑鼠指標,CSS 的 :hover 自然不會觸發。但 touchstart 近似 mouseover、touchend 近似 mouseout,可以搭出等效效果:
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 */
a:hover, a.hover { /* 你的 hover 效果 */ }
這樣做出來的連結會更像一顆實體按鈕,而且這套模擬可以用在任何元素上。實務上還要記得 touchend 有可能永遠不會發生(手指被系統中斷),所以最好也監聽 touchcancel 把狀態清乾淨。