图像加载时显示“正在加载"图标 [英] Display a Loading icon while images loads

查看:93
本文介绍了图像加载时显示“正在加载"图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 div 中显示一个背景图像/加载微调器,该图像将在其中加载图像,一旦完全加载,图像将显示,如下所示:

I want to show a background image/loading spinner inside a div that will load an image inside of it, the image will show once it's fully loaded doing something like this:

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

演示(在jQuery中)

如何使用Angular2/Ionic2拥有相同的功能?

How can I have the same using Angular2/Ionic2?

推荐答案

创建一个组件,该组件显示占位符图像,直到加载请求的图像为止,并隐藏请求的图像.加载图像后,您将隐藏占位符并显示图像.

Create a component that shows the placeholder image until the requested image is loaded, and hides the requested image. Once the image is loaded, you hide the placeholder and show the image.

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

看到它在柱塞中正常工作.

更新

现在,我对要求有了更好的了解,这是带有背景图像的解决方案.这有点hacky,我更喜欢原始的……

Now that I understand the requirements better, here's a solution with background image. It's a little hacky, and I like the original one better...

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

更新的监听器.

这篇关于图像加载时显示“正在加载"图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆