简体   繁体   中英

jQueryUI disable / cancel icon from being dragged in a sortable list?

I am having difficulty trying to disable the list elements from being dragged by the icon.

Each li has an icon, when clicked either removes or adds it into another list. However if you drag by its icon it removes or adds the item.

I want to be able to drag the li around, but stop the icons from being dragable on the li's.

I have a demo: http://jsfiddle.net/w3vvL/27/

I have tried a number of things with no success and I cant figure it out: -

    $( "#gallery li" ).draggable({
          cancel: "a.ui-icon",
          revert: "invalid",
          containment: "document",
          helper: "clone",
          cursor: "move"
        });
    $( ".ui-icon" ).disableSelection();

    //Get Dropped Item
    $("#trash").droppable({
         drop: function(event, ui) {
    $(ui.draggable).stop();

               }
    });

Any help would be greatly appreciated!

In your jsfiddle, I added the following:

$('.delete, .add').on('mousedown', function(e) {
    e.stopPropagation();
});

This stops the mousedown event from bubbling up, so it inhibits the draggable behaviour, when the icon (an a element inside the li ) is clicked.

HOWEVER, this is not a good solution! It adds event handlers to the a elements themselves, so it only adds handlers to the elements which exist when you call on . If you add a new item (I used the ADD button, luckily it was implemented), the fix doesn't apply . You would have to add the handler to any new items that are added.


We could do it a better way. We could add a handler to the containers instead:

$('#gallery, #trash').on('mousedown', '.ui-icon', function(e) {
    e.stopPropagation();
});

The second argument of on lets us specify a filter. The #gallery and #trash elements can receive mousedown events bubbling up from child elements, but we only want this handler to execute if the event originated from a .ui-icon . This is pretty good, we only have to set up event handlers once and there's only one per sortable container, so it's easier and more efficient.


I decided to check the API documentation , and found that there's a specific option to deal with this:

$("#gallery, #trash").sortable("option", "cancel", ".ui-icon");

which very cleanly tells the sortable widget not to allow sorting if it's started from a .ui-icon ! Instead of calling sortable("option") explicitly, you could add this option to the initialization of your sortables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM