下面是一个使用Angular实现响应式选项卡和下拉菜单的示例:
首先,在Angular项目中创建一个组件,比如TabDropdownComponent
。
tab-dropdown.component.html:
- {{ tab.title }}
-
{{ selectedTab.title }}
- {{ tab.title }}
{{ tab.content }}
tab-dropdown.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-tab-dropdown',
templateUrl: './tab-dropdown.component.html',
styleUrls: ['./tab-dropdown.component.css']
})
export class TabDropdownComponent {
tabs = [
{ title: 'Tab 1', content: 'Content 1', active: true },
{ title: 'Tab 2', content: 'Content 2', active: false },
{ title: 'Tab 3', content: 'Content 3', active: false },
{ title: 'Tab 4', content: 'Content 4', active: false }
];
selectedTab = this.tabs[0];
showDropdown = false;
selectTab(tab) {
this.tabs.forEach(t => t.active = false);
tab.active = true;
this.selectedTab = tab;
}
toggleDropdown() {
this.showDropdown = !this.showDropdown;
}
}
tab-dropdown.component.css:
.tab-container {
display: flex;
flex-direction: column;
}
.tab-header {
display: flex;
justify-content: flex-start;
}
.tab-header li {
cursor: pointer;
padding: 10px;
background-color: #eee;
}
.tab-header li.active {
background-color: #ccc;
}
.tab-header .dropdown {
position: relative;
}
.tab-header .dropdown ul {
position: absolute;
top: 100%;
left: 0;
z-index: 1;
display: none;
background-color: #eee;
padding: 10px;
list-style: none;
}
.tab-header .dropdown ul li {
cursor: pointer;
}
.tab-header .dropdown ul li:hover {
background-color: #ccc;
}
.tab-header .dropdown ul li:first-child {
margin-top: 10px;
}
.tab-header .dropdown ul li:last-child {
margin-bottom: 10px;
}
.tab-header .dropdown ul li:first-child,
.tab-header .dropdown ul li:last-child {
background-color: transparent;
cursor: default;
}
.tab-header .dropdown ul li:not(:first-child):not(:last-child):hover {
background-color: #eee;
}
.tab-header .dropdown ul li:not(:first-child):not(:last-child):active {
background-color: #ccc;
}
接下来,在需要使用该组件的地方,比如app.component.html
,添加以下代码:
最后,在app.module.ts
中将TabDropdownComponent
添加到declarations
数组中。
现在,您应该能够在应用程序中看到一个包含响应式选项卡和下拉菜单的组件。您可以根据需要自定义样式和功能。