輪播有的功能,應該都有
angular2及以上的版本應該均可以
動畫效果用的是angular自帶的animations
css沒有作進一步的處理,專一於js
作過測試應該沒有bug
功能
1.圖片自動輪播
2.每張圖片對應下面的小圓圈,紅色表明當前選中圖片
3.前進和後退按鈕作了節流處理
代碼
html
<p>
carousel works!
</p>
<ul [@carousel]='state' >
<li class='imgP' *ngFor='let img of imgs' (mouseenter)='stop()'
(mouseleave)='start()'
>
<!---->
<div *ngIf='img.state'>
<img [src]="url+img.name" >
</div>
</li>
</ul>
<div >
<div class='circle' [class.color]='img.state' *ngFor='let img of imgs'
(mouseenter)="circleEnter(img.id)" (mouseleave)='circleLeave()'
>
</div>
<div class='btn' (mouseenter)='stop()' (mouseleave)='start()'>
<input type="button" value="go" (click)="go()">
<input type="button" value="back" (click)="back()">
</div>
</div>
js
import { Component, OnInit } from '@angular/core';
import {trigger,style,transition,query,animate,group} from '@angular/animations'
@Component({
selector: 'app-carousel',
templateUrl: './carousel.component.html',
styleUrls: ['./carousel.component.css'],
animations:[
trigger('carousel',[
transition(':increment',[
group([
query(':enter',[
style({transform:'translateX(-100%)'}),
animate('1s')
]),
query(':leave',[
animate('1s',style({transform:'translateX(100%)'}))
])
])
]),
transition(':decrement',[
group([
query(':enter',[
style({transform:'translateX(100%)'}),
animate('1s')
]),
query(':leave',[
animate('1s',style({transform:'translateX(-100%)'}))
])
])
]),
])
]
})
export class CarouselComponent implements OnInit {
url:string='../../../assets/'
imgs=[
{id:1,name:'1.jpg',state:true},
{id:2,name:'2.jpg',state:false},
{id:3,name:'3.jpg',state:false}
]
state=0;
id:number;
i=0;
switch=true
execTime:number
constructor() { }
fn(){
this.i++;
if(this.i>this.imgs.length-1){
this.i=0;
}
this.imgs.forEach(val=>{val.state=false})
this.imgs[this.i].state=true;
this.state+=0.1;
}
ngOnInit() {
this.id=setInterval(this.fn.bind(this),3000)
}
stop(){
clearInterval(this.id)
}
start(){
this.id=setInterval(this.fn.bind(this),3000)
}
circleEnter(id){
//console.log(id);
this.i=id-1;
this.imgs.forEach(val=>{val.state=false})
this.imgs[id-1].state=true;
//this.state+=0.1;
this.stop();
}
circleLeave(){
this.start();
}
go(){
this.throttle(this.fn.bind(this),1500)
//this.fn()
}
back(){
let fn=function(){
//console.log('exec fn');
this.i--;
if(this.i<0){
this.i=this.imgs.length-1;
}
this.imgs.forEach(val=>{val.state=false})
this.imgs[this.i].state=true;
this.state-=0.1;
}
this.throttle(fn.bind(this),1500)
}
throttle(fn,interval){
if(new Date().getTime()-this.execTime>interval){this.switch=true}
console.log(this.switch);
if(this.switch){
fn();
this.switch=false;
this.execTime=new Date().getTime();
}
}
}
css
ul{
position:relative;
height:200px;
}
.imgP{
position:absolute;
list-style:none;
}
.circle{
width:10px;
height:10px;
border-radius:50%;
border:1px solid #000;
float:left;
}
.color{
background-color:red;
}