ionic2 使用slides制作滑动效果的类型选择栏
类似的效果如下图:
1. 生成一个component
- ionic g component MySlide
2. 在my-slide.html中添加代码:
- <ion-slides class="slide-title" [options]="mySlideOptions">
- <ion-slide *ngFor="let slide of slides; let i = index;">
- <div (click)="onClick(i)">
- <span class="slide-title-unit" [ngClass]="{'slide-title-active': selectedIndex == i}">{{slide}}</span>
- </div>
- </ion-slide>
- </ion-slides>
其中slides是一个数组,存放类型字符串,如上图显示的"推荐", "环球"等
3. 在my-slide.ts中添加代码:
- import {Component, Input, Output, EventEmitter} from '@angular/core';
- @Component({
- selector: 'my-slide',
- templateUrl: 'build/components/my-slide/my-slide.html'
- })
- export class MySlide {
- @Input("slides") slides: string[] = [];
- @Input("pageNumber") pageNumber: number = 5;
- @Output("slideClick") slideClick = new EventEmitter<number>();
- mySlideOptions;
- selectedIndex: number = 0;
- constructor() {
- }
- ngOnInit() {
- this.mySlideOptions = {
- loop: false,
- autoplay: false,
- initialSlide: 0,
- pager: false,
- slidesPerView: this.pageNumber,
- paginationHide: true,
- paginationClickable: true
- };
- }
- onClick(index) {
- this.selectedIndex = index;
- this.slideClick.emit(index);
- }
- }
Input参数slides,my-slide的属性传入,显示类型的字符串数组。
Input参数pageNumber,my-slide的属性传入,表示当前屏幕可以显示的类型数目,默认为5。
Output参数slideClick,当点击某个类型时,将点击的index返回给使用者。
4. my-slide.scss
- $slide-height-small: 40px;
- $slide-height-large: 50px;
- .slide-title {
- width: 100%;
- height: $slide-height-small;
- color: #666666;
- padding: 0;
- }
- .slide-title-unit {
- padding-bottom: 8px;
- font-size: 14px;
- height: $slide-height-small;
- line-height: $slide-height-small;
- }
- .slide-title-active {
- color: map_get($colors, primary);
- border-bottom: 3px solid map_get($colors, primary);
- }
其中slide-title-active表示选中时改变类型文字颜色以及下方显示横线。
5. 使用方法:
- <my-slide (slideClick)="onSlideClick($event)" [slides]="pageSlides" [pageNumber]="7"></my-slide>
最后,不要忘记在@Component中添加directives: [MySlide]
与其坐以待毙,不如自己现在努力.