* 创建自定义下拉选择器
(
options: { value: string; label: string }[],
currentValue: string,
onChange: (value: string) => void
)
| 1080 | * 创建自定义下拉选择器 |
| 1081 | */ |
| 1082 | private createCustomSelect( |
| 1083 | options: { value: string; label: string }[], |
| 1084 | currentValue: string, |
| 1085 | onChange: (value: string) => void |
| 1086 | ): HTMLElement { |
| 1087 | const container = document.createElement("div"); |
| 1088 | container.className = "milkup-custom-select"; |
| 1089 | |
| 1090 | const button = document.createElement("button"); |
| 1091 | button.className = "milkup-custom-select-button"; |
| 1092 | button.type = "button"; |
| 1093 | const currentOption = options.find((o) => o.value === currentValue); |
| 1094 | button.textContent = currentOption?.label || options[0].label; |
| 1095 | |
| 1096 | const dropdown = document.createElement("div"); |
| 1097 | dropdown.className = "milkup-custom-select-dropdown"; |
| 1098 | |
| 1099 | for (const option of options) { |
| 1100 | const item = document.createElement("div"); |
| 1101 | item.className = "milkup-custom-select-item"; |
| 1102 | if (option.value === currentValue) { |
| 1103 | item.classList.add("selected"); |
| 1104 | } |
| 1105 | item.textContent = option.label; |
| 1106 | item.dataset.value = option.value; |
| 1107 | item.addEventListener("click", (e) => { |
| 1108 | e.stopPropagation(); |
| 1109 | button.textContent = option.label; |
| 1110 | // 更新选中状态 |
| 1111 | dropdown.querySelectorAll(".milkup-custom-select-item").forEach((el) => { |
| 1112 | el.classList.remove("selected"); |
| 1113 | }); |
| 1114 | item.classList.add("selected"); |
| 1115 | container.classList.remove("open"); |
| 1116 | onChange(option.value); |
| 1117 | }); |
| 1118 | dropdown.appendChild(item); |
| 1119 | } |
| 1120 | |
| 1121 | button.addEventListener("click", (e) => { |
| 1122 | e.stopPropagation(); |
| 1123 | // 关闭所有其他下拉框 |
| 1124 | document.querySelectorAll(".milkup-custom-select.open").forEach((el) => { |
| 1125 | if (el !== container) { |
| 1126 | el.classList.remove("open"); |
| 1127 | } |
| 1128 | }); |
| 1129 | |
| 1130 | // 检测是否需要向上弹出 |
| 1131 | const buttonRect = button.getBoundingClientRect(); |
| 1132 | const viewportHeight = window.innerHeight; |
| 1133 | const spaceBelow = viewportHeight - buttonRect.bottom; |
| 1134 | const dropdownHeight = 240; // 最大高度 |
| 1135 | |
| 1136 | if (spaceBelow < dropdownHeight && buttonRect.top > spaceBelow) { |
| 1137 | container.classList.add("dropup"); |
| 1138 | } else { |
| 1139 | container.classList.remove("dropup"); |