楼层组件js实现
以下是一个楼层组件的 JavaScript 实现示例,包含核心功能和代码结构:
基础实现
class FloorComponent {
constructor(containerId, floors) {
this.container = document.getElementById(containerId);
this.floors = floors;
this.currentFloor = 0;
this.render();
}
render() {
this.container.innerHTML = '';
const floorList = document.createElement('div');
floorList.className = 'floor-list';
this.floors.forEach((floor, index) => {
const floorItem = document.createElement('div');
floorItem.className = `floor-item ${index === this.currentFloor ? 'active' : ''}`;
floorItem.textContent = `Floor ${floor}`;
floorItem.addEventListener('click', () => this.selectFloor(index));
floorList.appendChild(floorItem);
});
this.container.appendChild(floorList);
}
selectFloor(index) {
this.currentFloor = index;
this.render();
this.onFloorSelect(index);
}
onFloorSelect(index) {
console.log(`Selected floor: ${this.floors[index]}`);
}
}
使用示例
// 初始化楼层组件
const floors = ['B1', '1F', '2F', '3F', '4F'];
const floorComponent = new FloorComponent('floor-container', floors);
// 自定义选择回调
floorComponent.onFloorSelect = (index) => {
alert(`You selected ${floors[index]} floor`);
};
样式建议
.floor-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.floor-item {
padding: 12px;
background: #f0f0f0;
border-radius: 4px;
cursor: pointer;
}
.floor-item.active {
background: #2196F3;
color: white;
}
扩展功能
// 添加楼层
FloorComponent.prototype.addFloor = function(floorName) {
this.floors.push(floorName);
this.render();
};
// 移除楼层
FloorComponent.prototype.removeFloor = function(index) {
this.floors.splice(index, 1);
if (this.currentFloor >= this.floors.length) {
this.currentFloor = Math.max(0, this.floors.length - 1);
}
this.render();
};
动画效果实现
selectFloor(index) {
// 添加过渡动画
const prevActive = this.container.querySelector('.active');
if (prevActive) {
prevActive.classList.add('fade-out');
setTimeout(() => {
prevActive.classList.remove('fade-out');
this.currentFloor = index;
this.render();
this.onFloorSelect(index);
}, 300);
} else {
this.currentFloor = index;
this.render();
this.onFloorSelect(index);
}
}
该实现包含基础楼层选择功能、样式控制、扩展方法和动画效果,可根据实际需求进行调整和扩展。







