後台管理常需「選擇資料夾路徑」功能。傳統 <select> 無法呈現階層、難以搜尋。結合 PHP 遞迴掃描目錄 + jQuery mcDropdown 外掛,即可實作類似 IDE 側邊欄的樹狀下拉選單。
<?php
/**
* 遞迴掃描目錄,產出符合 mcDropdown 格式的 HTML 片段
*
* @param string $dir 起始目錄
* @param bool $recursive 是否掃描子目錄
* @param string &$html 輸出 HTML 字串(傳址)
* @param int &$counter 節點計數器(傳址,供 rel 屬性)
*/
function buildDirTree(string $dir, bool $recursive, string &$html, int &$counter): void
{
$handle = @opendir($dir);
if (!$handle) return;
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$full = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($full)) {
$html .= '' . htmlspecialchars($file) . '';
if ($recursive) {
buildDirTree($full, true, $html, $counter);
}
$html .= '
';
}
}
closedir($handle);
}
// ----- 產出完整選單 HTML -----
$counter = 1;
$menuHtml = '';
buildDirTree(__DIR__, true, $menuHtml, $counter);
// 移除空的
(mcDropdown 不需要)
$menuHtml = '';
$menuHtml = str_replace('
', '', $menuHtml);
// 嵌入模板
$tpl = file_get_contents(__DIR__ . '/template.html');
$tpl = str_replace('#categorymenu#', $menuHtml, $tpl);
$tpl = str_replace('#delim#', DIRECTORY_SEPARATOR, $tpl);
echo $tpl;
template.html<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="utf-8">
<title>目錄選擇器 Demo</title>
<link rel="stylesheet" href="lib/jquery.mcdropdown.css">
<script src="lib/jquery-3.6.0.min.js"></script>
<script src="lib/jquery.mcdropdown.js"></script>
<script src="lib/jquery.bgiframe.js"></script> <!-- IE6/7 相容 -->
<script>
$(function(){
$('#category').mcDropdown('#categorymenu', {
allowParentSelect: true,
delim: '#delim#' // 由 PHP 置換為 DIRECTORY_SEPARATOR
});
});
</script>
</head>
<body>
<p>請選擇目錄:<br>
<input type="text" id="category" name="category" value="" style="width:400px">
</p>
#categorymenu#
</body>
</html>
| 選項 | 預設 | 說明 |
|---|---|---|
allowParentSelect | false | true 時可選擇父節點(資料夾本身) |
delim | '/' | 值串接分隔符,PHP 端用 DIRECTORY_SEPARATOR |
autoHeight | true | 自動調整下拉高度 |
showSpeed | 'fast' | 展開動畫速度 |
uploads/2024/05/images)\ 在 JS 字串需雙重跳脫,範例已由 PHP 置換處理。PHP 遞迴掃描 + mcDropdown 可快速構建目錄選擇器,適合中小型專案或內部工具。長期維護專案請評估遷移至現代前端元件,獲得更好的無障礙支援、行動裝置體驗與維護性。