在组件中使用ViewChild来获取用于滚动的元素,然后在选项卡切换时手动更新scrollLeft属性。示例代码如下:
html文件:
{{tab.title}}
ts文件:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-tabs',
templateUrl: './tabs.component.html',
styleUrls: ['./tabs.component.css']
})
export class TabsComponent implements OnInit {
@ViewChild('tabsContainer', { static: true }) private tabsContainerRef: ElementRef;
tabs = [
{ title: 'Tab 1' },
{ title: 'Tab 2' },
{ title: 'Tab 3' },
{ title: 'Tab 4' },
{ title: 'Tab 5' },
{ title: 'Tab 6' },
{ title: 'Tab 7' },
{ title: 'Tab 8' },
];
selectedTab = this.tabs[0];
tabsWidth = 'auto';
constructor() { }
ngOnInit() {
this.calculateTabsWidth();
}
selectTab(tab) {
this.selectedTab = tab;
this.updateScrollLeft();
}
private calculateTabsWidth() {
this.tabsWidth = `${this.tabs.length * 120}px`;
}
private updateScrollLeft() {
if (this.tabsContainerRef.nativeElement.scrollWidth !== this.tabsContainerRef.nativeElement.clientWidth) {
const scrollLeft = this.selectedTab.getElementRef().nativeElement.offsetLeft - ((this.tabsContainerRef.nativeElement.clientWidth - this.selectedTab.getElementRef().nativeElement.clientWidth) / 2);
this.tabsContainerRef.nativeElement.scrollLeft = scrollLeft;
}
}
}