我想创建一个采集卡,应该是能够滚动由左到右的按钮。如果用它卡的容器太大,一个按钮应该会出现,如果我按一下按钮,然后向左滚动按钮就会出现,且容器应滚动。现在的问题是,它似乎像*ngIf
后,我点击其他元素上只检查。
容器看起来就像这样(这应该是一个播放列表):
我想过,也许该元件需要被重新集中,所以JavaScript的知道“嘿,好像我的scrollLeft改变”,但没有奏效。
我有两个按钮:
<button *ngIf="showLeftScroll()" mat-icon-button class="scroll-button-left" (click)="scrollLeft()"><mat-icon>keyboard_arrow_right</mat-icon></button>
<button *ngIf="isScrollable()" mat-icon-button class="scroll-button-right" (click)="scrollRight()"><mat-icon>keyboard_arrow_right</mat-icon></button>
和方法是:
isScrollable() {
const container = this.cardContainer.nativeElement;
const isScrollable = container.offsetWidth < container.scrollWidth;
const isNotAtTheEnd = container.offsetWidth + container.scrollLeft !== container.scrollWidth;
return (isScrollable && isNotAtTheEnd);
}
showLeftScroll() {
return this.cardContainer.nativeElement.scrollLeft > 0;
}
scrollRight() {
this.cardContainer.nativeElement.scrollLeft += 600;
this.cardContainer.nativeElement.focus();
}
scrollLeft() {
this.cardContainer.nativeElement.scrollLeft -= 600;
this.cardContainer.nativeElement.focus();
}
此刻会发生什么?
我点击按钮向右滚动,其滚动的权利,但对于向左滚动按钮只有当我点击任何其他元素上出现。
应该发生什么?
滚动到左边的按钮应该在右边,当我点击按钮用于向右滚动的瞬间显示。
要强制*ngIf
指令的即时更新,呼叫ChangeDetectorRef.detectChanges()
以滚动方式结束:
constructor(private changeDetectorRef: ChangeDetectorRef) { }
scrollRight() {
this.cardContainer.nativeElement.scrollLeft += 600;
this.changeDetectorRef.detectChanges();
}
scrollLeft() {
this.cardContainer.nativeElement.scrollLeft -= 600;
this.changeDetectorRef.detectChanges();
}