在图像加载时显示加载图标

Display a Loading icon while images loads

我想在 div 中显示背景 image/loading 微调器,它将在其中加载图像,图像将在完全加载后显示,执行如下操作:

   <div style="background-image:url('imageThatWillAppearBeforeLoad')"></div>

Demo (In jQuery)

如何使用 Angular2/Ionic2 获得相同的内容?

创建一个组件,在加载请求的图像之前显示占位符图像,并隐藏请求的图像。加载图像后,隐藏占位符并显示图像。

@Component({
  selector: 'image-loader',
  template: `<img *ngIf="!loaded" src="url-to-your-placeholder"/>
    <img [hidden]="!loaded" (load)="loaded = true" [src]="src"/>`
})
export class ImageLoader {
  @Input() src;
}

查看它在 Plunker 中的工作情况。

更新

现在我对要求有了更好的了解,这里有一个带背景图片的解决方案。有点乱,我更喜欢原版...

@Directive({
  selector: '[imageLoader]'
})
export class ImageLoader {
  @Input() imageLoader;

  constructor(private el:ElementRef) {
    this.el = el.nativeElement;
    this.el.style.backgroundImage = "url(http://smallenvelop.com/demo/image-loading/spinner.gif)";
  }

  ngOnInit() {
    let image = new Image();
    image.addEventListener('load', () => {
      this.el.style.backgroundImage = `url(${this.imageLoader})`;
    });
    image.src = this.imageLoader;
  }
}

Updated plunker.

这是我的一份副本

我终于用 CSS 解决了这个问题!当图像在 ionic 2 中加载时,ion-img 标签没有任何 class。然而,当图像最终加载时,ion-img 标签得到 class "img-loaded".

这是我的解决方案:

  <ion-img [src]="img.src"></ion-img>
  <ion-spinner></ion-spinner>

还有我的 CSS :

.img-loaded + ion-spinner {
  display:none;
}

就用这个功能

loadImage(element: HTMLElement, imagePath: string, spinnerPath: string) {
  element.tagName === 'img'
    ? element.setAttribute('src', spinnerPath)
    : (element.style.background = `url(${spinnerPath}) 50% 50% no-repeat`);
  const image = new Image();
  image.crossOrigin = 'Anonymous';
  image.src = imagePath;
  image.onload = () => {
    element.tagName === 'img'
      ? element.setAttribute('src', imagePath)
      : (element.style.background = `url(${imagePath})`);
  };
}

您不必担心您的元素是图像还是 div 或其他什么?

示例,如果您不知道如何使用它

ngOnInit() {
  const myElement = document.getElementsByClassName('my-element')[0];
  // or however you want to select it.
  const imagePath = 'path/to/image.png';
  const spinnerPath = 'path/to/spinner.gif'; // or base64 spinner url.

  this.loadImage(myElement, imagePath, spinnerPath);
}

编码愉快