轮播有的功能,应该都有
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;}