angular TV端焦点移动插件-画廊效果实现
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键盘的时候跳转详情页
最终界面: