加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular2 directive 让图片垂直居中

发布时间:2020-12-17 09:25:26 所属栏目:安全 来源:网络整理
导读:这个做法最终的效果是横向宽度100%,高度最高为300px,当图片的宽度大于高度时,图片会垂直居中,如果图片的宽度小于高度时,横向100%,超过300px的部分将会被隐藏,效果如下: 做法是使用栅格布局,每行显示4个,页面代码如下: div class="row" div class=

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

做法是使用栅格布局,每行显示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;
    }
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读