繁体   English   中英

图像加载时显示“正在加载”图标

[英]Display a Loading icon while images loads

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

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

演示(在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中工作。

更新资料

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

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

更新了插件

这是我的一篇文章的副本

我终于用CSS解决了这个问题! 当图像在ionic 2中加载时,ion-img标签没有任何类别。 但是,当最终加载图像时,ion-img标签将获得“ 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})`);
  };
}

您不必担心您的元素是image或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);
}

快乐编码😉

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM