这个做法最终的效果是横向宽度100%,高度最高为300px,当图片的宽度大于高度时,图片会垂直居中,如果图片的宽度小于高度时,横向100%,超过300px的部分将会被隐藏,效果如下:
<div class="row"> <div class="col-md-3" *ngFor="let l of lists; let i = index"> <div class="card"> <div class="card-block"> <div class="form-group cover" [style.background-color]="ranColor(i)"> <img [src]="l.url" imgresize> </div> <div class="form-group"> <label class="form-control-label">名字</label> <select class="form-control"> <option>Jason Stanson</option> <option>黄立行</option> <option>高圆圆</option> <option>刘亦菲</option> </select> </div> </div> </div> </div> </div>
ts代码:
//这个是背景颜色的代码,网上找的,颜色很柔和,看上去很舒服 colorList: any = ['#E3A05C','#b2be7e','#726f80','#390d31','#5a3d42','#14446a','#113f3d','#3c4f39','#5f5c33','#b3d66e','#fff5f6','#b2c8bb','#458994'];
//这个是在循环的过程中添加背景色 ranColor(index?: number) { return this.colorList[index]; }
img { width: 100%; } .cover { height: 300px; overflow: hidden; }
重要的地方是使用angular2 的directive如何让图片居中,思路是使用属性绑定,获得图片的高度和宽度,进行计算,得到一个margin-top的值,将这个值赋值给图片对象,这里绑定了margin-top属性,监听了窗口的load和window.resize事件:
import {Directive,ElementRef,HostBinding,HostListener} from "@angular/core"; @Directive({ selector: '[imgresize]' }) export class ImgResizeDirective { _dom: any; _margin_top: any; constructor(private elem: ElementRef) { this._dom = this.elem; } @HostBinding('style.marginTop.px') get width() { return this._margin_top ? this._margin_top : 0; } @HostListener('load') load() { let h = this._dom.nativeElement.offsetHeight; let w = this._dom.nativeElement.offsetWidth; if (300 > h) { this._margin_top = (300 - h)/2; } if (300 < h) { this._margin_top = 0; } } @HostListener('window:resize') resizeWindow() { let h = this._dom.nativeElement.offsetHeight; let w = this._dom.nativeElement.offsetWidth; if (300 > h) { this._margin_top = (300 - h)/2; } if (300 < h) { this._margin_top = 0; } } }