爲什麼在子頁面點擊無法關閉父頁面下拉框?
答:
1. 通常在沒有iframe時,當我們做一個下拉框的功能,當鼠標在頁面上的其它位置點擊一下時,這個下拉框就隱藏掉了,這個功能很容易做,給document綁定onmousedown或onclick即可。
2. 如果頁面上有iframe時,鼠標點擊在iframe內時,包含iframe的document是不響應任何事件的,所以需要給iframe綁定類似的事件,當iframe指向的是第三方的內容時,還在考慮跨域的問題,因此通過操作iframe的document是行不通的,還好有document.activeElement可供我們使用,解決方案如下:
var IframeOnClick = {
resolution: 200,
iframes: [],
interval: null,
Iframe: function() {
this.element = arguments[0];
this.cb = arguments[1];
this.hasTracked = false;
},
track: function(element, cb) {
this.iframes.push(new this.Iframe(element, cb));
if (!this.interval) {
var _this = this;
this.interval = setInterval(function() { _this.checkClick(); }, this.resolution);
}
},
checkClick: function() {
if (document.activeElement) {
var activeElement = document.activeElement;
for (var i in this.iframes) {
if (activeElement === this.iframes[i].element) { // user is in this Iframe
if (this.iframes[i].hasTracked == false) {
this.iframes[i].cb.apply(window, []);
this.iframes[i].hasTracked = true;
}
} else {
this.iframes[i].hasTracked = false;
}
}
}
}
};
再然後調用它就可以了:
IframeOnClick.track(document.getElementById("iFrame"), function() {
alert('a click');
});
其實主要通過焦點匹配來進行監聽的,所以你在它的點擊函數裏改變一下焦點 $body.focus(); 這樣在子頁面隨便哪個地方點擊都可以執行alert()函數
其他小知識:
在網頁中,如何獲取嵌入網頁中的iframe內的document 對象呢?
1、第一種訪問方法
這種寫法估計很多人都沒有用過:
document.getElementById(‘iframe1’).Document
注意:這裏的獲取document對象使用的是大寫的Document, 若寫成小寫的document對象則指當前網頁的document對象。
測試方法:
document.getElementById(‘iframe1’).document.writeln(‘test is ok’); //結果:當前網頁頁面輸出test is ok
document.getElementById(‘iframe1’).Document.writeln(‘test is ok’); //結果:嵌入網頁(iframe1)頁面輸出test is ok
//iframe的document對象
document.getElementById('iframe1').Document
//當前網頁的document對象
document.getElementById('iframe1').document
2、第二種訪問方法
document.getElementById(‘iframe1’).contentWindow.document
iframe裏面的元素觸發父窗口元素事件的jquery代碼
例如父窗口定義了一個事件。
top:
$(dom1).bind(‘topEvent’, function(){});
那麼iframe裏面的元素怎樣觸發父窗口dom1的事件呢?這樣嗎?
$(dom1, parent.document).trigger(‘topEvent’);
看似正確,實則誤導人。
因爲父窗口的jquery對象與iframe裏面的jquery對象實際爲兩個對象(function),iframe裏面的jquery並不會觸發另一個jquery對象定義的事件。除非你在iframe這樣定義了:
iframe:
self.$ = parent.$;
所以解決的方法很簡單:
parent.$(dom1,parent.doucment).trigger(‘topEvent’);
調用父jquery執行該事件就行了。
話說iframe應該不必再引進jquery文件的,與父窗口共用一個jquery就行了,這樣很環保。