這是一個粗略的實現,需要更多的工作!請注意,這是在Ionic 2環境中實施的。
概述
創建「導言」組成的包含覆蓋和工具提示/提示。我選擇將此組件作爲Ionic 2 popover打開(Ionic將自動添加疊加層)。將相關元素作爲參數傳入引入組件。創建一個絕對定位元素相對於另一個元素(在頁面上)的指令。撒上scss。
重要提示:就我而言,頁面上有圖片需要時間加載。位置數據是不正確的,直到我等待加載圖像。這是jQuery的相同,並通過包裝命令在解決:
$(window).load(function() {
});
現在,我有一個簡單的打開延遲介紹頁面的計時器。
MY-position.ts
該指令頂部/設置左側元件相對於另一參考元件的一個(在頁面上)。
import { Directive, Input, OnInit, ElementRef, Renderer } from '@angular/core';
/**
* Inspired by jQuery position: https://api.jqueryui.com/1.8/position/
*/
@Directive({
selector: '[my-position]',
host: {
'[style.position]': '"absolute"',
}
})
export class MyPosition implements OnInit {
@Input('my-position') of: any;
@Input('my') myInput: string;
@Input('at') atInput: string;
@Input('offset') offsetInput: string;
my: string[];
at: string[]
offset: string[];
constructor(
private element: ElementRef,
private renderer: Renderer
) {}
ngOnInit() {
if (this.of.nativeElement) {
let top: number;
let left: number;
// Default inputs.
if (!this.myInput) {
this.myInput = 'top left';
}
if (!this.atInput) {
this.atInput = 'top left';
}
if (!this.offsetInput) {
this.offsetInput = '0 0';
}
this.my = this.myInput.split(' ');
this.at = this.atInput.split(' ');
this.offset = this.offsetInput.split(' ');
// Get reference element position.
let rect = this.of.nativeElement.getBoundingClientRect();
// Set new top/left values.
left = rect.left + parseInt(this.offset[0]);
top = rect.top + parseInt(this.offset[1]);
// Adjust top/left values for on element position.
if (this.at[0] == 'center') {
left += rect.width/2;
}
if (this.at[1] == 'center') {
top += rect.height/2;
}
// Position element.
this.renderer.setElementStyle(this.element.nativeElement, 'top', top + 'px');
this.renderer.setElementStyle(this.element.nativeElement, 'left', left + 'px');
}
}
}
introduction.html
添加工具提示/提示的介紹頁面。添加我的位置指令並將相關元素作爲參數傳遞。添加額外的位置參數(根據需要)。
<div class="hint" [my-position]="hintRef1" my="left top" at="left top" offset="0 105">This is an app hint!</div>
introduction.ts
獲取hintRef1元件參數的構造函數。
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private viewController: ViewController
) {
// Get elements (passed as parameters from page) to use as references (to position hints).
this.hintRef1 = navParams.get('hintRef1');
this.hintRef2 = navParams.get('hintRef2');
this.hintRef3 = navParams.get('hintRef3');
}
home.html做爲
添加名稱來引用元素(必須是駱駝情況下),例如
<div #hintRef1 ...
home.ts
主頁上獲取參考元素(作爲參數傳遞)。
// Pass position reference elements to introduction popover.
@ViewChild('hintRef1') hintRef1;
@ViewChild('hintRef2') hintRef2;
@ViewChild('hintRef3') hintRef3;
將參考元素作爲參數傳遞給介紹頁面。
let popover = this.popoverController.create(IntroductionPage, {
'hintRef1': this.hintRef1,
'hintRef2': this.hintRef2,
'hintRef3': this.hintRef3
}, { cssClass: 'introduction' });
一個組件可以是另一個組件的子項,並通過CSS定位嗎?應該避免使用DOM操作,是的。 – Askanison4
我不確定。我更新了這個問題:目標是能夠在幫助/提示文本可以放置在元素頂部的任何頁面頂部創建疊加層。 –
答案是否足以讓你繼續下去? – Askanison4