angular TV端焦點移動外掛-畫廊效果實現
阿新 • • 發佈:2020-12-24
angularTV端焦點移動外掛 ng-tv-focusable
安裝
npm i -S ng-tv-focusable
app.module.ts中
import { TvFocusableModule } from 'ng-tv-focusable';
@NgModule({
declarations: [...],
imports: [
...
TvFocusableModule
]
})
tv.component.ts元件中的html(css有點多,此處就不寫了):
<div class="tv-box"> <div class="item-box"> <div class="perspective"> <div class="item" focusable *ngFor='let item of list ;let index = index' [ngStyle]="{ 'left': -100 * index - index * 20 +'px', 'z-index': activeIndex === index ? 1100 :1000 - abs(activeIndex - index) * 5, 'transform': activeIndex < index ? 'rotateY(-30deg)':activeIndex === index?'rotateY(0deg)':'rotateY(30deg)' }" (left)="left(index,$event)" (right)="right(index,$event)" (down)="nofocus()" (up)="nofocus()" (click)="skip(index)"> <img [src]="item.url"/> <span class="txt">{{item.title}}</span> </div> </div> </div> <div class="bottom-img"><img src="../../assets/tv/r-menu.png"/></div> <div class="loading" *ngIf="loadingShow"><img src="../../assets/tv/loadingCancel.gif"/></div> </div>
tv.component.ts元件中的js
import { $tv } from 'ng-tv-focusable'; ngAfterViewInit() { $tv.init({distanceToCenter:true }); $tv.setScrollEl(document.querySelector('.item-box')) $tv.requestFocus($tv.getElementByPath("//div[@class='perspective']/div[3]")); } ngOnDestroy() {$tv.resetScrollEl(); } abs(num){ return Math.abs(num)} skip(index){ if(index === 8) { this.loadingShow = true; setTimeout(() => { this.router.navigate(['example7-detail']); },1000) } } nofocus(event){ $tv.requestFocus(event.target); } right(index, event){ if(index === this.list.length - 1 ){return;} this.activeIndex = index + 1; } left(index,event){ if(index === 0 ){return; } this.activeIndex = index - 1; }
解釋:
1.指令focusable設定可獲取焦點的div
2.新增自定義事件(left),(right),按左右按鍵來計算當前層級以及縮放比例
3.新增自定義事件(up),(down),按上下按鍵的時候阻止焦點跳動
4.新增click事件,按ok鍵盤的時候跳轉詳情頁
最終介面: