問題描述
我想在 div
中顯示一個(gè)背景圖像/加載微調(diào)器,它將在其中加載一個(gè)圖像,圖像將在完全加載后顯示,執(zhí)行如下操作:
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?
推薦答案
創(chuàng)建一個(gè)組件,在加載請(qǐng)求的圖像之前顯示占位符圖像,并隱藏請(qǐng)求的圖像.加載圖像后,隱藏占位符并顯示圖像.
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;
}
查看它在 Plunker 中的工作.
See it working in Plunker.
更新
現(xiàn)在我更好地理解了要求,這里有一個(gè)帶有背景圖片的解決方案.有點(diǎn)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;
}
}
更新插件.
這篇關(guān)于加載圖像時(shí)顯示加載圖標(biāo)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!