【问题标题】:Click-event on iframe?iframe 上的点击事件?
【发布时间】:2012-05-13 13:42:02
【问题描述】:

我有一个简单的 iFrame……

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

我知道我无法捕捉框架内元素上的点击事件,但 iFrame 本身上的简单点击或鼠标按下怎么样?

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

这对我不起作用!

【问题讨论】:

  • 您是否在iframe 中显示来自您的服务器 的页面?
  • 实际上是的,来自我页面的子域。所以我在“url.com”上,而 iframe src 是“subdomain.url.com”……现在我在本地,只是想知道如何在点击它时捕获点击事件。

标签: jquery iframe click


【解决方案1】:

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');

【讨论】:

  • 这当然只有在 iframe 内容来自同一个域时才有效,对吧?
  • 它是否也适用于来自第 3 方的 iframe?根据我的测试,这似乎不是。
  • @clwen 如果 iframe 来自不同的域,由于 jQuery 的跨域请求处理,它将无法工作。您可以尝试使用:jQuery.support.cors = true; 强制执行跨站点脚本(从 jQuery 1.5 开始)。可以查看文档here
【解决方案2】:

由于网络浏览器的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)
        }
    });
});

享受吧!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2012-11-06
  • 2013-02-11
  • 2020-05-19
相关资源
最近更新 更多