jQuery iframe 上的点击事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10572227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Click-event on iframe?
提问by matt
I have a simple iFrame …?
我有一个简单的 iFrame ......?
<iframe src="url" width="980px" height="90px" id="inviteFrame" name="inviteFrame" scrolling="no"></iframe>
I know I can't catch click events on elements inside the frame but how about a simple click or mousedown on the iFrame itself?
我知道我无法在框架内的元素上捕捉点击事件,但是在 iFrame 本身上进行简单的点击或鼠标按下怎么样?
$('#inviteFrame').click(function() {
console.log('test');
$(this).attr('height', '140px');
});
This doesn't work for me!
这对我不起作用!
回答by Zuul
jQuery has a method, called .contents(), that when used on an iframe
element returns the document of the iframe.
jQuery 有一个方法,称为.contents(),当在iframe
元素上使用时,返回 iframe 的文档。
// Get a reference to the iframe document
var iframeDoc = $('#inviteFrame').contents().get(0);
Now you can bind an event to it, get the dimensions, get styles of various elements, etc:
现在您可以将事件绑定到它,获取维度,获取各种元素的样式等:
// 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');
回答by Vince
You cannot do this because of web browser's same origin policy.
由于 Web 浏览器的同源策略,您不能这样做。
But you can use a workaround with the blur event and mouseover/mouseout events. That's how works my iframeTracker jQuery plugin, designed to track clicks on iframes : https://github.com/finalclap/iframeTracker-jquery
但是您可以使用模糊事件和鼠标悬停/鼠标移出事件的解决方法。这就是我的 iframeTracker jQuery 插件的工作原理,旨在跟踪 iframe 上的点击:https: //github.com/finalclap/iframeTracker-jquery
Here is an example :
这是一个例子:
jQuery(document).ready(function($){
$('.iframe_wrap iframe').iframeTracker({
blurCallback: function(){
// Do something when iframe is clicked (like firing an XHR request)
}
});
});
Enjoy !
享受 !