jQuery代码不起作用

时间:2017-06-14 18:08:30

标签: javascript jquery html

我试图在这里实现从其他线程获取的这个javascript代码: css 'pointer-events' property alternative for IE,但我无法使其发挥作用。当我点击目标iframe元素时,所需的“点击”效果并未实现。我也在jsfiddle.com上试过但它也不起作用......我一定错过了一些重要的东西。有人能告诉我如何在jsfiddle中正确地执行此代码吗?非常感谢你。

$(document).ready(function() {
    $(document).on('mousedown', '#iframe_1', function (e) {
        $(this).hide();
        var BottomElement = document.elementFromPoint(e.clientX, e.clientY);
        $(this).show();
        $(BottomElement).mousedown(); //Manually fire the event for desired underlying element
        return false;
    });
});

iframe甚至不会隐藏...... https://jsfiddle.net/c4vttL6t/

1 个答案:

答案 0 :(得分:0)

事件未被触发,因为您必须在iframe的内容上注册事件,而不是在iframe中注册。你可以通过以下方式实现这一目标:

var iframeBody = $('body', $('#iframe-1')[0].contentWindow.document);
$(iframeBody).on('mousedown', function(event) {
    $('#iframe-1').hide();

    return false;
});

但要注意,如果您要从其他网站加载内容,则无法使用。

代码来自here

更新:也许这段代码可以帮助您,考虑到iframe是一个在另一个之上:

// iframe-1 mousedown handler
var iframeBody1 = $('body', $('#iframe-1')[0].contentWindow.document);
$(iframeBody1).on('mousedown', function(e) {
    //$('#iframe-1').hide();
    // alert mousedown 1
    alert('mousedown 1');
    return false;
});

// iframe-2 mousedown handler
var iframeBody2 = $('body', $('#iframe-2')[0].contentWindow.document);

// search and trigger mousedown handler on X element
var iframeDocument1 = $("#iframe-1")[0].contentWindow.document;

// iframe-2 mousedown handler
$(iframeBody2).on('mousedown', function(e) {
    //$('#iframe-2').hide();
    // calculate position relative to element if necessarily 
    $(iframeDocument1.elementFromPoint(e.pageX, e.pageY)).mousedown();

    // Alert mousedown 2
    alert('mousedown 2');
    // as you are using iframe I think hide and show is not necessary
    // because you can trigger mousedown handler on a particular element
    //$('#iframe-2').show();
    return false;
});