Jus*_*nte 51 iframe jquery onclick
我在页面上有一个iframe,来自第三方(广告).我想在点击iframe时发出点击事件(记录一些内部统计数据).就像是:
$('#iframe_id').click(function() {
//run function that records clicks
});
Run Code Online (Sandbox Code Playgroud)
..基于HTML:
<iframe id="iframe_id" src="http://something.com"></iframe>
Run Code Online (Sandbox Code Playgroud)
我似乎无法得到任何变化的工作.思考?
Tra*_*Guy 37
iframe没有'onclick'事件,但您可以尝试在iframe中捕获文档的click事件:
document.getElementById("iframe_id").contentWindow.document.body.onclick =
function() {
alert("iframe clicked");
}
Run Code Online (Sandbox Code Playgroud)
编辑 虽然这不能解决您的跨站点问题,但FYI jQuery已更新为与iFrames配合使用:
$('#iframe_id').on('click', function(event) { });
Run Code Online (Sandbox Code Playgroud)
Update 1/2015 iframe解释的链接已被删除,因为它已不再可用.
注意 如果iframe来自与主页不同的域,则上述代码将不起作用.您仍然可以尝试使用评论中提到的黑客.
Vin*_*nce 16
尝试使用这个:iframeTracker jQuery插件,像这样:
jQuery(document).ready(function($){
$('.iframe_wrap iframe').iframeTracker({
blurCallback: function(){
// Do something when iframe is clicked (like firing an XHR request)
}
});
});
Run Code Online (Sandbox Code Playgroud)
Kev*_*vin 14
我试图找到一个更独立的更好的答案,所以我开始考虑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
});
});
});
Run Code Online (Sandbox Code Playgroud)
仅当框架包含来自同一域的页面时才起作用(不违反同源策略)
看到这个:
var iframe = $('#your_iframe').contents();
iframe.find('your_clicable_item').click(function(event){
console.log('work fine');
});
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以通过进行如下操作来模拟焦点/单击事件。(改编自影响Iframe的$(window).blur事件)
$(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");
})Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
141907 次 |
| 最近记录: |