2012-05-13 107 views
3

我有一个简单的iFrame ...iframe上的点击事件?

<iframe src="url" width="980px" height="90px" id="inviteFrame" name="inviteFrame" scrolling="no"></iframe> 

我知道我不能赶上点击框内的元素,但如何对事件简单的点击或的mousedown对自身的iFrame?

$('#inviteFrame').click(function() { 
    console.log('test'); 
    $(this).attr('height', '140px'); 
}); 

这不适合我!

+1

你是否在'iframe'中显示**你的服务器**的页面? – VisioN

+0

其实是的,从我的网页的子域。所以我在“url.com”和iframe src是“subdomain.url.com”...现在我在本地,只是想知道如何在点击它时捕捉点击事件。 – matt

回答

7

jQuery有一个方法,名为.contents(),当在iframe元素上使用时返回iframe的文档。

// Get a reference to the iframe document 
var iframeDoc = $('#inviteFrame').contents().get(0); 

现在你可以将事件绑定到它,得到的尺寸,款式获得各种元素等:

// Get width of iframe document 
$(iframeDoc).width(); 

// Get height of iframe document 
$(iframeDoc).height(); 

// Bind event to iframe document 
$(iframeDoc).bind('click', function(event) { 
    // do something 
}); 

// Get the style of an element in the iframe 
$('div', iframeDoc).css('backgroundColor'); 
+1

这当然只适用于iframe内容来自同一个域,对吗? – matt

+0

它是否也适用于来自第三方的iframe?这似乎不是根据我的测试。 – clwen

+1

@clwen如果Iframe来自不同的域,由于jQuery的跨域请求处理,它将不起作用。你可以尝试使用:'jQuery.support.cors = true;'强制跨站脚本(从jQuery 1.5开始)。您可以查看文档[此处](http://api.jquery.com/jQuery.support/)。 – Zuul

1

你不能这样做,因为Web浏览器的same origin policy这一点。

但是,您可以使用blur事件和mouseover/mouseout事件的解决方法。这是如何工作的我iframeTracker jQuery插件,旨在跟踪在I帧点击:https://github.com/finalclap/iframeTracker-jquery

下面是一个例子:

jQuery(document).ready(function($){ 
    $('.iframe_wrap iframe').iframeTracker({ 
     blurCallback: function(){ 
      // Do something when iframe is clicked (like firing an XHR request) 
     } 
    }); 
}); 

享受!

+0

嗨@Vince,我使用你的插件来做这样的事情,但有一些问题。你能在这里提供我的其他问题的任何帮助吗? http://stackoverflow.com/questions/25891050/accuratly-catch-clicks-on-an-iframe – tripRev