在瀏覽器中,滑鼠光標是使用者判斷「這裡能不能點、能不能拖」的重要線索。透過在不同情境切換光標樣式,就能替介面加上一層低成本的引導。以下把 cursor 的定義、標準值、擴充值與自訂方式整理成一份可查閱的筆記。
cursor 用於指定指標 berada 在元素上時顯示的形狀。
[<uri>,]*[auto | default | pointer | crosshair | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help | progress] | inheritCSS2 提供的選項相對有限,但已涵蓋絕大多數常見情境:
url 自定義光標檔案的路徑 default 預設光標,通常是箭頭 auto 由瀏覽器自行判斷 crosshair 十字準線 pointer 手型指針,代表可點擊 move 移動 e-resize 向東(右)縮放 ne-resize 向東北縮放 nw-resize 向西北縮放 n-resize 向北(上)縮放 se-resize 向東南縮放 sw-resize 向西南縮放 s-resize 向南(下)縮放 w-resize 向西(左)縮放 text 文字輸入游標 wait 忙碌等待 help 說明與提示
CSS3 追加了更多語意化的值,能更精準地表達操作意圖。
cursor: none cursor: context-menu cursor: cell cursor: alias cursor: copy cursor: grab cursor: grabbing cursor: zoom-in cursor: zoom-out cursor: vertical-text cursor: no-drop cursor: not-allowed cursor: all-scroll cursor: ew-resize cursor: ns-resize cursor: nesw-resize cursor: nwse-resize cursor: col-resize cursor: row-resize
需注意這些擴充值的支援度在舊版瀏覽器上並不平均,正式上線前建議先確認目標裝置的相容情況。
部分瀏覽器另外提供了加上廠商行首的私有版本,寫法上通常會與標準屬性並列,讓支援的瀏覽器往後覆蓋:
cursor: -webkit-grab; cursor: -moz-grab; cursor: -webkit-grabbing; cursor: -moz-grabbing; cursor: -webkit-zoom-in; cursor: -moz-zoom-in; cursor: -webkit-zoom-out; cursor: -moz-zoom-out;
所有主流瀏覽器都支援副檔名為 .cur 的光標檔,Chrome、Firefox、Safari 也接受一般的圖片格式。
這裡有一個很容易踩到的細節:使用 url() 時,後面必須接一個逗號與某個通用關鍵字作為後備值,否則整條宣告會被視為無效。
/* 錯誤寫法 */
cursor: url('m.cur');
/* 正確寫法 */
cursor: url('m.cur'), auto;
連結預設就是手型指針,這正是使用者判斷可點擊依據的來源;同理,任何自製的點擊元件都應該補上 cursor: pointer。
另一個實用小技巧是搭配 title 屬性:當元素需要補充說明時,把光標改為 help,視覺暗示會更明確。
span[title] {
cursor: help;
border-bottom: 1px solid gray;
}
<div><span title="Cascading Style Sheets">CSS</span> is much too interesting</div>
光標看似只是細節,但它承擔了大量「不用文字也能溝通」的介面語意,值得在設計階段一併規劃。