在 Web 開發中,常需要讓使用者透過點擊箭頭來增加或減少數值,這就是所謂的「Spinner(微調器)」效果。若要快速實現這類互動,jQuery UI 提供了現成的 spinner 元件,僅需幾行程式碼即可完成。
<input> 元素。$(selector).spinner() 初始化。<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<title>jQuery UI Spinner Demo</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script>
$(function() {
$("#spinner").spinner({
min: 0,
max: 100,
step: 1
});
});
</script>
</head>
<body>
<label for="spinner">選擇數量:</label>
<input id="spinner" name="value">
</body>
</html>
| 選項 | 說明 |
|---|---|
| min | 允許的最小值 |
| max | 允許的最大值 |
| step | 每次點擊增減的步長 |
| disabled | 設為 true 可停用元件 |
可監聽 spin 或 change 事件,在使用者操作時即時驗證或更新其他欄位:
$("#spinner").on("spinchange", function(event, ui) {
console.log("目前數值:" + $(this).val());
});
善用 jQuery UI Spinner 可大幅減少客製化數字輸入介面的開發時間,並提供良好的使用者體驗。若專案已使用 jQuery,這是最快上手的方案之一。
