如何获取与放置事件位置对应的范围对象

How to get a range object that correspond to the position of a drop event?

本文关键字:位置 事件 对象 范围 何获取 获取      更新时间:2023-09-26

我想将图像拖放到一个aloha可编辑字段中。

我正在看at.tapo.aloha.plugins. image插件,看起来很棒。

然而,我需要适应这个插件,以便与缩略图工作。我拖拽缩略图,当我把它拖拽到aloha可编辑器中时,html代码被动态修改,以便使用真实的图像。

    GENTICS.Aloha.EventRegistry.subscribe(GENTICS.Aloha, 'editableCreated', function(event, editable) {
        var the_obj = editable.obj;
        jQuery(editable.obj).bind('drop', function(event){
            var e = event.originalEvent;
            var files = e.dataTransfer.files;
            var count = files.length;
            if (count < 1) {
                var node = e.dataTransfer.mozSourceNode;
                if (node.tagName === 'IMG') {
                    var html = '<img ....>'; //build the real image html code  
                    /// The current selection but I want the drop position
                    var range = GENTICS.Aloha.Selection.getRangeObject();
                    if (!jQuery.isEmptyObject(range)) {
                        GENTICS.Utils.Dom.insertIntoDOM(jQuery(html), range, the_obj);
                    }
                    return false;
                }
                return true;
            }
    }

当在aloha字段中选择某些内容时,它可以正常工作。我可以得到一个范围,并将html插入到DOM的选择位置。

然而,我想得到一个范围对象,对应于我的图像被丢弃的地方。怎么做呢?

谢谢你的建议。

据我所知,通常没有一种简单的方法可以做到这一点。您可以获取落点的像素坐标(可能来自mousemove事件),然后尝试获取该点的范围。对于这个任务,下面这个问题的答案很好地总结了它:

在FF/Webkit中从像素位置创建一个折叠区域

Tim Down告诉我没有简单的方法,我最终使用了一个变通方法:

GENTICS.Aloha.EventRegistry.subscribe(GENTICS.Aloha, 'editableCreated', function(event, editable) {
    var the_obj = editable.obj;
    jQuery(editable.obj).bind('drop', function(event){
        setTimeout(function () {
            //at this point the html is updated and can be postprocessed 
            //in order to turn thumbnails into the real image
            //force the focus in order to make sure that the editable is activated
            //this will cause the deactivated event to be triggered, and the content to be saved
            the_obj.focus(); 
        }, 0);
    });
});