import { Component, OnInit, Input, ElementRef, Renderer, ViewChild } from '@angular/core';
/**
* 文字上下滚动轮播
*/
@Component({
selector: 'scroll-list',
template:`
`
})
export class ScrolllistComponent implements OnInit {
@Input() interval
@Input() size
@Input() list
@Input() height = 14
@ViewChild('scrollList') scrollList
currTimer
currIdx = 0
isPlaying = true
items = []
constructor(public element:ElementRef, public renderer:Renderer) {
this.size = this.size || 1;
}
ngOnInit() {
this.renderer.setElementStyle(this.scrollList.nativeElement,
'height', this.height*this.size + 'px');
}
ngOnChanges(){
this.clearItems();
this.resetFn();
this.currTimer = setTimeout(() => {
this.timerFn();
}, this.interval || 3000);
}
// 清除items
clearItems = () => {
this.items = [];
}
// 添加item
addItem = (item, element) => {
item.$element = element;
item.$index = this.items.length;
this.items.push(item);
if (item && item.$index>=0 && item.$index == this.size - 1) {
this.select(this.items[0]);
}
}
// 选择item并滚动显示
select = (item) => {
if(!item || !(item.$index>=0)) return;
for(let j = 0;j < this.size;j++ ) {
var t = this.items[(item.$index + j) % this.items.length];
this.renderer.setElementStyle(t.$element.nativeElement,'opacity','1');
this.renderer.setElementStyle(t.$element.nativeElement,'top',this.height*j + 'px');
t.active = true;
}
for(let k = 0;k < this.items.length - this.size;k++ ) {
let t = this.items[(item.$index + this.size + k) % this.items.length];
if(k == this.items.length - this.size - 1){
this.renderer.setElementStyle(t.$element.nativeElement,'opacity','0');
this.renderer.setElementStyle(t.$element.nativeElement,'top','-'+this.height+'px');
}else{
this.renderer.setElementStyle(t.$element.nativeElement,'opacity','0');
this.renderer.setElementStyle(t.$element.nativeElement,'top',this.height*(this.size + k) + 'px');
}
}
}
// 计时器
timerFn = () => {
if (this.isPlaying) {
this.currIdx = ++ this.currIdx % this.items.length;
this.select(this.items[this.currIdx]);
this.restartFn();
} else {
this.pause();
}
}
// 重启计时器
restartFn = () => {
this.resetFn();
this.currTimer = setTimeout(this.timerFn, this.interval);
}
// 重置
resetFn = () => {
if(this.currTimer) clearTimeout(this.currTimer);
}
play = () => {
if (!this.isPlaying) {
this.isPlaying = true;
this.restartFn();
}
}
pause = () => {
this.isPlaying = false;
this.resetFn();
}
}
@Component({
selector: 'scroll-item',
template:`
`
})
export class ScrollItemComponent{
constructor(public element:ElementRef, public renderer:Renderer, public scrollListCtrl:ScrolllistComponent) {
this.scrollListCtrl.addItem(this, this.element);
}
}