如何使用HTML或JavaScript创建矩形,实现点击按钮展示可选时段功能
完整实现代码
<!DOCTYPE html> <html> <head> <title>预约时段选择</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .slot-container { display: flex; flex-wrap: wrap; gap: 10px; margin: 15px 0; } .slot-item { border: 1px solid #ccc; padding: 10px 15px; border-radius: 4px; cursor: pointer; background: #fff; min-width: 80px; text-align: center; } .slot-item:hover { border-color: #2196F3; background: #e3f2fd; } .slot-item.active { background: #2196F3; color: #fff; border-color: #1976D2; } .hidden { display: none; } </style> </head> <body> <label>Location</label> <select name="location"> <option>Location 1 </option> <option>Location 2 </option> <option>Location 3 </option> <option>Location 4 </option> </select><br><br> <button> Check Slots </button> <br> <label> Choose a slot: </label> <div id="slotContainer" class="slot-container hidden"></div> <script> // 不同地点对应的可预约时段,可替换为实际接口返回的数据 const locationSlots = { 'Location 1': ['09:00', '10:00', '11:00', '14:00', '15:00', '16:00'], 'Location 2': ['09:30', '11:30', '13:00', '14:30', '16:30'], 'Location 3': ['10:00', '12:00', '15:00', '17:00'], 'Location 4': ['08:30', '10:30', '13:30', '15:30', '18:00'] } const checkBtn = document.querySelector('button') const locationSelect = document.querySelector('select[name="location"]') const slotContainer = document.getElementById('slotContainer') checkBtn.addEventListener('click', () => { const selectedLocation = locationSelect.value.trim() const slots = locationSlots[selectedLocation] // 清空旧时段 slotContainer.innerHTML = '' // 渲染新时段 slots.forEach(slot => { const slotEl = document.createElement('div') slotEl.className = 'slot-item' slotEl.textContent = slot // 选中时段逻辑 slotEl.addEventListener('click', () => { document.querySelectorAll('.slot-item').forEach(item => item.classList.remove('active')) slotEl.classList.add('active') }) slotContainer.appendChild(slotEl) }) // 显示时段区域 slotContainer.classList.remove('hidden') }) </script> </body> </html>
实现说明
- 样式完全匹配矩形时段块的交互效果,支持 hover 高亮、点击选中变色
- 内置了4个地点对应的模拟时段数据,可直接替换为后端接口返回的真实时段数据
- 时段选中状态可直接对接后续表单提交逻辑,无需额外修改
内容的提问来源于stack exchange,提问作者Warning Yi
相关产品推荐
相关产品推荐

