iframe上的点击事件?

4

I have a simple iFrame … 

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

我知道无法捕获框架内部元素的点击事件,但是在iFrame本身上进行简单的点击或mousedown怎么样?

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

这对我不起作用!


1
你是否在 iframe 中展示来自你的服务器的页面? - VisioN
实际上,是从我的页面的子域中嵌入的。所以我在"url.com"上,iframe的src是"subdomain.url.com" ……现在我只是想知道如何在本地捕获单击事件。 - matt
2个回答

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
它是否也适用于来自第三方的 iframe?根据我的测试,似乎不行。 - clwen
1
如果Iframe来自不同的域名,由于jQuery的跨域请求处理,它将无法工作。您可以尝试使用以下方法强制进行跨站点脚本编写(从jQuery 1.5开始):jQuery.support.cors = true;。您可以在此处查看文档:http://api.jquery.com/jQuery.support/。 - Zuul

1

由于浏览器的同源策略(same origin policy),你无法做到这一点。

但是你可以通过模糊事件和mouseover/mouseout事件使用解决方法。这就是我的iframeTracker jQuery插件的工作原理,它旨在跟踪iframe上的点击: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)
        }
    });
});

享受吧!


嗨@Vince,我正在使用您的插件来实现类似的功能,但遇到了一些问题。您能在这里回答我的另一个问题吗?http://stackoverflow.com/questions/25891050/accuratly-catch-clicks-on-an-iframe - tripRev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接