如果元素是iframe,如何捕获Click事件?

时间:2013-01-03 10:48:06

标签: javascript jquery

我在id为div1的div中添加了一个带有youtube embed url的iframe。我想在iframe点击时做点什么。

我正在使用这个jquery代码,但它无效。

$('#div1 iframe').bind('click', function(){
         alert('clicked on iframe');
});

4 个答案:

答案 0 :(得分:0)

我不确定您是否拥有iframe的ID。但您可以尝试捕捉iframe中文档的点击:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

虽然这不能解决您的跨网站问题,但仅供参考jQuery has been updated to play well with iFrames

$('#iframe_id').bind('click', function(event) { });

答案 1 :(得分:0)

function iframeclick() {
    document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}

答案 2 :(得分:0)

我们可以在jQuery中使用achive,而在javascript中也可以使用

$('.inner iframe').bind('click', function(){
             alert('clicked on iframe');
    });

答案 3 :(得分:0)

这是一个使用JS的解决方案-并且为我解决了一个类似的问题,如果单击iFrame,我需要关闭父项的一些下拉列表

  public static iFrameClickHandler = {
        iFrame: undefined,
        mouseOverIframe: false,
        mouseOver: function() {
            this.mouseOverIframe = true;
        },
        mouseLeave: function() {
            this.mouseOverIframe = false;
            window.focus();
        },
        windowBlur: function() {
            if (this.mouseOverIframe) this.fireClickEvent();
        },
        fireClickEvent: function() {
            // do what you wanna do here
        },
        init: function() {
            this.mouseOver = this.mouseOver.bind(this);
            this.mouseLeave = this.mouseLeave.bind(this);
            this.windowBlur = this.windowBlur.bind(this);
            this.iFrame = document.querySelector('class/id of your iframe wrapper');
            this.iFrame.addEventListener('mouseover', this.mouseOver);
            this.iFrame.addEventListener('mouseleave', this.mouseLeave);
            window.addEventListener('blur', this.windowBlur);
            window.focus();
        },
        destroy: function() {
            this.iFrame.removeEventListener('mouseover', this.mouseOver);
            this.iFrame.removeEventListener('mouseleave', this.mouseLeave);
            window.removeEventListener('blur', this.windowBlur);
        }
    }