我在页面上有一个来自第三方(广告)的iframe。当iframe被点击时,我想触发一个点击事件(以记录一些内部统计信息)。类似于:
$('#iframe_id').click(function() {
//run function that records clicks
});
根据以下HTML内容:
<iframe id="iframe_id" src="http://something.com"></iframe>
我似乎无法让这个的任何变体起作用。 有什么想法吗?
虽然 iframe 没有 'onclick' 事件,但是你可以尝试捕获 iframe 内文档的点击事件:
document.getElementById("iframe_id").contentWindow.document.body.onclick =
function() {
alert("iframe clicked");
}
编辑 尽管这并不能解决您的跨站问题,但是请注意jQuery已经更新以与iFrames良好协作。
$('#iframe_id').on('click', function(event) { });
更新1/2015 由于该链接已不再可用,因此已移除有关iframe解释的链接。
注意 如果iframe来自于与宿主页面不同的域,上述代码将无法工作。您仍然可以尝试使用评论中提到的一些技巧。
我试图寻找一个更独立的答案,于是开始思考jQuery如何处理事件和自定义事件。由于click(来自jQuery)只是任何事件,我认为我所要做的就是在iframe的内容被点击时触发该事件。因此,这是我的解决方案。
$(document).ready(function () {
$("iframe").each(function () {
//Using closures to capture each one
var iframe = $(this);
iframe.on("load", function () { //Make sure it is fully loaded
iframe.contents().click(function (event) {
iframe.trigger("click");
});
});
iframe.click(function () {
//Handle what you need it to do
});
});
});
尝试使用这个:iframeTracker jQuery插件,像这样:
jQuery(document).ready(function($){
$('.iframe_wrap iframe').iframeTracker({
blurCallback: function(){
// Do something when iframe is clicked (like firing an XHR request)
}
});
});
仅当框架包含来自相同域的页面时才有效(不违反同源策略)
请参见:
var iframe = $('#your_iframe').contents();
iframe.find('your_clicable_item').click(function(event){
console.log('work fine');
});
您可以通过以下方式模拟聚焦/点击事件。 (改编自$(window).blur event affecting Iframe)
$(window).blur(function () {
// check focus
if ($('iframe').is(':focus')) {
console.log("iframe focused");
$(document.activeElement).trigger("focus");// Could trigger click event instead
}
else {
console.log("iframe unfocused");
}
});
//Test
$('#iframe_id').on('focus', function(e){
console.log(e);
console.log("hello im focused");
})
我试了所有建议的答案,但都没有解决我的问题。最终我采用以下方法解决了类似的情况:
<a href="http://my-target-url.com" id="iframe-wrapper"></a>
<iframe id="iframe_id" src="http://something.com" allowtrancparency="yes" frameborder="o"></iframe>
CSS样式(当然,确切的定位应根据应用程序要求进行更改):
#iframe-wrapper, iframe#iframe_id {
width: 162px;
border: none;
height: 21px;
position: absolute;
top: 3px;
left: 398px;
}
#alerts-wrapper {
z-index: 1000;
}
$(window).load(function(){
$("#ifameid").contents().on('click' , 'form input' , function(){
console.log(this);
});
});
jQuery('.class_in_iframe',jQuery('[id="id_of_iframe"]')[0].contentWindow.document.body).on('click',function(){
console.log("triggered !!")
});
根据您绑定点击事件的时间,您可能会遇到一些时间问题,但它将把事件绑定到正确的窗口/文档。不过,实际上绑定到 iframe 窗口可能会获得更好的结果。您可以像这样执行:
var iframeWin = $('iframe')[0].contentWindow;
iframeWin.name = 'iframe';
$(iframeWin).bind('click', function(event) {
//Do something
alert( this.name + ' is now loaded' );
});
或许有点老了,但对于那些试图处理同域策略的人来说可能会很有用。
let isOverIframe = null;
$('iframe').hover(function() {
isOverIframe = true;
}, function() {
isOverIframe = false;
});
$(window).on('blur', function() {
if(!isOverIframe)
return;
// ...
});