用戶在 `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Select 導航跳轉</title>
<style>
.nav-select {
padding: 12px 16px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
background: #fff;
cursor: pointer;
min-width: 280px;
}
.nav-select:focus { outline: none; border-color: #0088bb; box-shadow: 0 0 0 3px rgba(0,136,187,.2); }
.centered { text-align: center; margin: 40px auto; max-width: 400px; }
noscript { display: block; margin-top: 12px; color: #666; }
</style>
</head>
<body>
<form action="/goto" class="centered" method="get">
<select id="navSelect" class="nav-select">
<option value="" selected disabled>請選擇頁面...</option>
<option value="/page/a.html">頁面 A:跨字段校驗</option>
<option value="/page/b.html">頁面 B:單選按鈕操作</option>
<option value="/page/c.html">頁面 C:字段聯動賦值</option>
<option value="/page/d.html">頁面 D:郵編驗證</option>
<option value="/page/e.html">頁面 E:郵箱驗證</option>
</select>
<noscript>
<input type="submit" value="前往 →">
</noscript>
</form>
<script>
// 模塊化寫法,避免全局污染
var NavSelect = (function () {
function init(selectId) {
var select = document.getElementById(selectId);
if (!select) return;
// 重置為首項 (防止瀏覽器緩存導致殘留選中)
select.selectedIndex = 0;
// 綁定 change 事件
select.addEventListener('change', function () {
var url = this.value;
if (url) {
// 可選:確認對話框
// if (!confirm('確定要跳轉到 ' + this.options[this.selectedIndex].text + ' 嗎?')) {
// this.selectedIndex = 0; return;
// }
window.location.href = url;
}
});
// 防止頁面緩存導致 back 時不觸發 onload (舊瀏覽器兼容)
window.addEventListener('unload', function () {});
}
return { init: init };
})();
// DOMContentLoaded 早於 load,無需等待圖片
document.addEventListener('DOMContentLoaded', function () {
NavSelect.init('navSelect');
});
</script>
</body>
</html>
noscript 降級:JS 禁用時顯示提交按鈕,表單提交到服務端由後端重定向DOMContentLoaded 重置選中狀態select.addEventListener('change', function () {
var url = this.value;
var text = this.options[this.selectedIndex].text;
if (!url) return;
// 彈出確認,用戶取消則重置選項
if (confirm('確定前往「' + text + '」嗎?')) {
window.location.href = url;
} else {
this.selectedIndex = 0;
}
});
// 假設使用簡單 hash 路由或 history API
select.addEventListener('change', function () {
var route = this.value; // 如 "#/page/a"
if (!route) return;
if (window.router) {
// Vue Router / React Router / 自定義 router
window.router.push(route);
} else if (route.startsWith('#')) {
location.hash = route;
} else {
// 降級:重新加載
location.href = route;
}
this.selectedIndex = 0; // 重置,允許連續跳轉同一頁
});
<label for="navSelect" class="visually-hidden">選擇導航頁面</label>
<select id="navSelect" aria-label="選擇導航頁面">...</select>
<style>
.visually-hidden {
position: absolute; width: 1px; height: 1px;
padding: 0; margin: -1px; overflow: hidden;
clip: rect(0,0,0,0); white-space: nowrap; border: 0;
}
</style>
<select> 導航是輕量級頁面跳轉的經典模式。核心要點:change 事件驅動、value 存 URL、selectedIndex=0 重置、noscript 降級、unload 破壞緩存。現代項目中多被下拉組件庫替代,但原生 Select 無依賴、語義正確、無障礙完美,仍是簡單場景的最優選。