jQuery:拖放图像?

时间:2015-02-16 16:28:27

标签: javascript jquery image

我正在使用jquery和jquery ui进行简单的拖放和调整Web应用程序的大小。

我遇到的问题是,我需要在未选择图像时移除手柄,并在选择图像时再次显示它们。

我可以使用DIV现在没有任何问题,但是当我使用图像<img>而不是div时,一旦图像角落的手柄消失,我就无法得到它们再次出现!

我在这里创建了一个完全正常的jsfiddle来演示这个问题。 http://jsfiddle.net/7btkn17q/

我在DIV使用了1,在<img>使用了1,因此您可以自己查看问题。

在上面的示例中,将书籍图像拖放到DIV Bellow中,然后将它们放在那里,单击图像外的某个位置,手柄栏将消失。要取回手柄,您需要再次单击图像。

正如您所看到的,带有<img>标记的图片并不会使句柄重新出现,但是图像是div的背景,会使句柄重新出现。

这是使手柄在点击时显示和消失的代码:

        $(document).click(function(e) {
    // matches all children of droppable, change selector as needed
    if( $(e.target).is("#droppable .drag") ) {
        $(e.target).find(".ui-resizable-handle").show();
        $("#tools").show();
    }
    else {
        $("#droppable").find(".ui-resizable-handle").hide();
        $("#tools").hide();
    }
});

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

这是因为img位于具有div类的drag内。 img本身与

不匹配
.is("#droppable .drag")

条件,因为它不是.drag

您需要在单击元素的祖先中查找drag类。 jQuerys closest这样做:

if( $(e.target).closest(".drag").length > 0 )
    //also when putting handles, need to put them on the right element
    $(e.target).closest(".drag").find(".ui-resizable-handle").show();

Updated fiddle

答案 1 :(得分:0)

如果您在单击图像时希望显示拖动控制柄,则需要在图像的父级上执行查找,因为它是作为目标返回的图像。 (img是手柄的兄弟姐妹)

//    if( $(e.target).is("#droppable .drag") ) {
if( $(e.target).is("#droppable .drag img") ) { // if this then the big book one works as the image is picking up the click
    //$(e.target).find(".ui-resizable-handle").show(); // click on the div
    $(e.target).parent().find(".ui-resizable-handle").show(); // as img is sibling to handles, you need to get the parent, then do the find. 

http://jsfiddle.net/7btkn17q/4/

相关问题