javascript之iframe 中的 jquery Draggable 不会点击

落叶无声 阅读:114 2026-10-29 21:35:05 评论:0

我已经在 iframe 中从其父级创建了一个可拖动对象,并且我想在单击该可拖动对象时附加一个事件。

可拖动功能可以自行工作,所有单击功能也可以自行工作,但是一旦将两者混合在一起,左键单击事件就会停止工作。如果我删除 iframe 并将可拖动和单击绑定(bind)放在单独的页面中,它就可以正常工作。

parent.html

<iframe id="siteframe" src="http://jsfiddle.net/kyT6N/show/light/"> 

parent.js

$('#siteframe').load(function () { 
 
    $('#siteframe').contents().find('.draggable').draggable({ delay:200, iframeFix: true}); 
 
    $('#siteframe').contents().find('.draggable').bind('mouseup',function() { 
        alert('mouse up'); 
    });   
 
    $('#siteframe').contents().find('.draggable').click(function() { 
        alert('click'); 
    }); 
    $('#siteframe').contents().find('.draggable').on('click', function() { 
        alert('click'); 
    }); 

});

iframe.html

<div class="draggable">draggable</div> 

JSFiddle 代码: http://jsfiddle.net/A5T3Q/

JSFiddle 演示: http://jsfiddle.net/A5T3Q/show/light/

编辑:

进一步调查后,似乎是 iframeFix: true 选项与点击功能混淆,我猜这是因为它覆盖了 iframe?有什么办法可以解决这个问题吗?

请您参考如下方法:

我认为这是 jquery ui 在 mousedown 事件发生后立即创建 iframeFix mask 太快的问题,但延迟仅用于 mousestart 控件。因此可以通过添加函数 _iframeFix 来优化。

_iframeFix: function(event){ 
    //patch for iframe 
    var o=this.options; 
    if(o.iframeFix === true){ 
        $("div.ui-draggable-iframeFix").each(function() { 
            this.parentNode.removeChild(this); 
        }); 
    } 
 
    $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { 
        $('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>') 
        .css({ 
            width: this.offsetWidth+"px", height: this.offsetHeight+"px", 
            position: "absolute", opacity: "0.001", zIndex: 1000 
        }) 
        .css($(this).offset()) 
        .appendTo("body"); 
    }); 
} 

去掉_mouseCapture函数中的iframe掩码代码,并在延迟后创建iframe掩码。 另外,您应该为 iframe 中的拖动元素添加 mouseup 事件句柄以结束超时控制

    if(o.iframeFix&&o.delay){ 
       that.element 
            .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); 
    } 

最后在_mouseup函数中,清除mouseup句柄,清除超时

_mouseUp: function(event) { 
    $(document) 
        .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) 
        .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); 
 
    var o=this.options; 
    if(o.iframeFix&&o.delay){ 
       mouseHandled = false; 
       this.element 
            .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); 
    } 
    if(this._mouseDelayTimer) clearTimeout(this._mouseDelayTimer); 
 
    if (this._mouseStarted) { 
        this._mouseStarted = false; 
 
        if (event.target === this._mouseDownEvent.target) { 
            $.data(event.target, this.widgetName + '.preventClickEvent', true); 
        } 
 
        this._mouseStop(event); 
    } 
 
    return false; 
}, 


标签:JavaScript
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号