Click-event on iframe?

我是研究僧i 提交于 2019-12-01 05:18:21

问题


I have a simple 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?

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

This doesn't work for me!


回答1:


jQuery has a method, called .contents(), that when used on an iframe element returns the document of the 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');



回答2:


You cannot do this because of web browser's same origin policy.

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

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 !



来源:https://stackoverflow.com/questions/10572227/click-event-on-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!