viewChild
使用 viewchild 等开发了一个轮播图组件
html
<div class="container">
<div class="image-slider" (scroll)="handleScroll($event)" #imageSlider>
<img *ngFor="let slider of sliders" [src]="slider.imgUrl" [alt]="slider.caption">
</div>
<div class="nav-section">
<span [ngClass]="{'select-button-select':idx === selectIndex}" *ngFor="let _ of sliders;let idx = index;" class="select-button">
</span>
</div>
</div>
ts
import { Component, OnInit, Input, ViewChild, ElementRef, ViewChildren, QueryList, Renderer2, AfterViewInit, OnDestroy } from '@angular/core';
export interface ImageSlider {
imgUrl: string;
link: string;
caption: string;
}
@Component({
selector: 'app-image-slider',
templateUrl: './image-slider.component.html',
styleUrls: ['./image-slider.component.less']
})
export class ImageSliderComponent implements OnInit, AfterViewInit, OnDestroy {
@Input() sliders: ImageSlider[] = [];
@ViewChild('imageSlider', { static: true }) imgSlider: ElementRef;
@Input() intervalBySecond = 2;
public intervalId: any;
public selectIndex = 0;
constructor(private rd2: Renderer2) { }
ngOnInit(): void {
// this.imgs.forEach(item => (item.nativeElement.style.height = '100px'));
}
ngAfterViewInit(): void {
this.intervalId = setInterval(() => {
this.rd2.setProperty(this.imgSlider.nativeElement,
'scrollLeft',
((this.getIndex(++this.selectIndex) % this.sliders.length) * this.imgSlider.nativeElement.scrollWidth) / this.sliders.length);
}, this.intervalBySecond * 1000);
}
getIndex(idx: number): number {
return idx >= 0 ? idx : this.sliders.length - (Math.abs(idx) % this.sliders.length);
}
handleScroll(ev) {
const radio = ev.target.scrollLeft * this.sliders.length / ev.target.scrollWidth;
this.selectIndex = Math.round(radio);
}
ngOnDestroy(): void {
clearInterval(this.intervalId)
}
}
css
.container {
position: relative;
overflow: hidden;
}
.image-slider {
display: flex;
overflow-x: scroll;
scroll-behavior: smooth;
-webkit-overflow-scrolling: touch;
scroll-snap-type: x mandatory;
}
.image-slider img {
width: 100%;
height: 160px;
}
.nav-section {
position: absolute;
bottom: 0;
width: 100%;
opacity: .5;
color: #fff;
background-color: #000;
display: flex;
justify-content: flex-end;
align-items: stretch;
}
.nav-section .select-button {
display: flex;
width: 10px;
height: 10px;
background-color: #fff;
text-decoration: none;
border-radius: 5px;
margin: 5px;
}
.nav-section .select-button-select {
background-color: red;
}
ImageSlider 为外部传入的数据
Tips
设置滚动条媳妇效果:
scroll-behavior: smooth;//平滑滚动
-webkit-overflow-scrolling: touch;//属性控制元素在移动设备上是否使用滚动回弹效果.
scroll-snap-type: x mandatory;滚动吸附(需深入学习)