angular2 directive 让图片垂直居中

这个做法最终的效果是横向宽度100%,高度最高为300px,当图片的宽度大于高度时,图片会垂直居中,如果图片的宽度小于高度时,横向100%,超过300px的部分将会被隐藏,效果如下:

101805_Ngev_2499632.png

做法是使用栅格布局,每行显示4个,页面代码如下:

<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];
}

CSS代码如下,内容很少:

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;
    }
  }
}

转载于:https://my.oschina.net/u/2499632/blog/871350

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值