Angular2x中使用iFrame( 之二)(实用、赞)

前几天写了《Angular2x中使用iFrame (实用、赞)》为了呈现ifram内嵌页面的全部内容要利用到window.postMessage方法,并且在嵌入的html文件中要加入javascript代码来处理,今天经Tony指出其实有更便捷的方法,改动如下 :
【父页面 html】

<meta charset="utf-8" />
<ion-header style="display:none">
    <ion-navbar>
        <ion-title>
            签到有奖
        </ion-title>
    </ion-navbar>
</ion-header>
<ion-content>
    <div class="iframe-box" style="height: 100%">
        <!--注意: 必须加上*ngIf="htmlFileUrl", 否则返回上一级有会出'Cannot GET /null' 错误(偶发性)-->
        <iframe *ngIf="htmlFileUrl" [src]="htmlFileUrl" 
                frameborder="0" 
                allowtrancparency="true" 
                style="border:0px; width: 100%; border: 1px solid red; height: 100%"
                ></iframe>
    </div>
    <div class="footer-bar">
        <button ion-button>立即签到</button>
    </div>
</ion-content>

改动有3处:
1、iframe 删除 scrolling="no" 设置,让iframe支持滚动;
2、iframe-box 和 iframe 加上 height: 100%, 令iframe的高度与页面容器高度一致;
3、删除[ngStyle]="getiFrameHeight()" ,有了上面第2点,这个计算的函数已无意义;

【子页面 html】

<head>
    <meta charset="utf-8" />
</head>

<img src="http://localhost:3073/htmlfile/MarketAction/9E395AC5-6B64-4B8E-95E6-0ABD46BCB589/202001131729000.jpeg" style="width:100%" />
<P style='font-size: 18px;'>
    你好吗!
</P>
<div>
    <span style='font-size: 12px; color: orange;'>你猜猜!</span>
    <span style="font-size:1.8rem; color: red; font-weight: 800; margin-left: 10px;">错了!</span>>
</div>

改动有1处:
1、head内的script标签被删除 ,因再无需再将高度通知父页面,所以删去;

【主页面ts】
 

...
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'


@IonicPage({
    name: 'sign-in',
})
@Component({
    selector: 'sign-in',
    templateUrl: 'sign-in.html'
})
export class SignInPage {
    ...
    private htmlFileUrl: SafeResourceUrl;

    constructor(
        ...
        private sanitizer: DomSanitizer
    ) {
       ...
    }

    ngOnInit() {
        this.loadData();
    }

    private loadData() {
        let params = {
        ...
        };
        this.appService.callBo("xxx", "xxx", params).subscribe((res) => {
            if (res.ErrCode == 0) { 
                let fileUrl = res.Data.HtmlFileUrl;                 
                this.htmlFileUrl = his.sanitizer.bypassSecurityTrustResourceUrl(fileUrl);
            } else {
                this.utils.showError(res.ErrMsg);
            }
        });
    }

    private submit() {
        //
    }
}

改动有3处:
1、getiFrameHeight() 被去掉;
2、变量iFrameHeight被去掉;
3、ngOnInit() 方法用于接收子页面的window.addEventListener被去掉;

【总结】
1、经过一轮改动代码简洁了许多,维护也简单了
2、两种方的区别是在于:
     第1种:iframe与子面页高度一样,用页面滚动
     第2种:iframe与当前页面高度一样,用iframe滚动

3应用场景:
    第1种方法:无按钮紧随iframe之后或固定在底部都适用;
    第2种方法:只适用于点击按钮固定在底部;


 



 

发布了214 篇原创文章 · 获赞 292 · 访问量 332万+

猜你喜欢

转载自blog.csdn.net/chelen_jak/article/details/104022049