Ela*_*ley 11 javascript angular
我有这个角度项目,我有一个填充页面的大背景图像和一个带有链接的简单侧边栏,点击后,将用另一个图像(来自cdn)更改背景的URL.由于这些图像相当大,它们需要一两秒才能加载并且它很明显,我想添加一个预加载器,但我不确定如何在角度2中完成.
在我的HTML中我有这个:
<section class="fullsizebg image-bg" [ngStyle]="{'background-image': 'url(' + urlImage + ')'}"></section>
Run Code Online (Sandbox Code Playgroud)
变量urlImage填充在组件的构造函数中,侧边栏链接在单击时更改它的值,使用一个简单的函数,如下所示:
generateImage(data: any){
this.urlImage = 'http://example.com/mycdn/'+this.data.url+'.jpg';
}
Run Code Online (Sandbox Code Playgroud)
因此,网址实际上会立即更改,但图像需要加载一些.我想添加一个加载gif或类似的东西,以保持图像变化顺利给用户,而不是像现在一样跳跃.
Sup*_*miu 18
一种方法是使用Blob获取图像并将其存储在img组件中,这样您就可以完成加载过程了,并且可以添加加载gif:
@Component({
selector:'loading-image',
template:'<img alt="foo" [src]="src"/>'
})
export class ExampleLoadingImage{
public src:string = "http://example.com/yourInitialImage.png";
constructor(private http:Http){}
generateImage(data: any): void {
this.src = 'http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif'; //Just a random loading gif found on google.
this.http.get('http://example.com/mycdn/'+this.data.url+'.jpg')
.subscribe(response => {
let urlCreator = window.URL;
this.src = urlCreator.createObjectURL(response.blob());
});
}
}
Run Code Online (Sandbox Code Playgroud)
注意:你应该输入你的数据参数,打字是确保一致性在你的代码,一个很好的办法any只应作为一个小丑一样Object在Java.
j2L*_*L4e 11
该解决方案利用了角度和浏览器已经提供的角度.图像加载由浏览器完成,无需自己处理任何数据或DOM.
我已经在Chrome 53上对此进行了测试,并且它运行良好.
这是你的元素,它的背景改变了:
<div class="yourBackgroundClass" [style.background-image]="'url(' + imgUrl + ')'"></div>
Run Code Online (Sandbox Code Playgroud)
要预取图像,我们使用未显示的图像标记.额外制作position: absolute并将其移出视图或使其非常小,这样做会很好,这样它就不会干扰您的实际内容.
<img [src]="imgPreloadUrl" (load)="imgUrl = imgPreloadUrl" hidden>
Run Code Online (Sandbox Code Playgroud)
通过设置imgPreloadUrl,img's src由角度更新,浏览器将图像加载到不可见img标签中.一旦完成,onload我们就会开火imgUrl = imgPreloadUrl.Angular现在更新style.background-image实际背景和背景图像立即切换,因为它已经加载到隐藏图像中.
虽然imgUrl !== imgPreloadUrl我们可以显示一个微调器来指示加载:
<div class="spinner" *ngIf="imgUrl !== imgPreloadUrl"></div>
Run Code Online (Sandbox Code Playgroud)
测试:
<button (click)="imgPreloadUrl = 'https://upload.wikimedia.org/wikipedia/commons/2/24/Willaerts_Adam_The_Embarkation_of_the_Elector_Palantine_Oil_Canvas-huge.jpg'">test</button>
Run Code Online (Sandbox Code Playgroud)
使用图像对象 (Plunker演示 ⇗)
tmpImg: HTMLImageElement; // will be used to load the actual image before showing it
generateImage(data: any){
this.urlImage = 'http://example.com/mycdn/'+ 'loading_GIF_url'; // show loading gif
let loaded = () => { // wait for image to load then replace it with loadingGIF
this.urlImage = 'http://example.com/mycdn/' + this.data.url+'.jpg';
}
// background loading logic
if(this.tmpImg){
this.tmpImg.onload = null; // remove the previous onload event, if registered
}
this.tmpImg = new Image();
this.tmpImg.onload = loaded; // register the onload event
this.tmpImg.src = 'http://example.com/mycdn/'+this.data.url+'.jpg';
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14225 次 |
| 最近记录: |