jQuery UI draggable and adding class on drag event

2019-06-22 15:11发布

问题:

I am trying to add a class to the draggable event using jQuery UI.

However the following code that I've written is not working as expected;

$(function () {
    $('ul.sortable div.draggable').draggable({
        start: function(event, ui) { ui.helper.addClass('move'); },
    });
});

Essentially I am trying to add a drop shadow (using the move class) to the div.draggable. What am I doing wrong as the drag event works, but the drop shadow does not appear?

Thanks in advance..

回答1:

From the jQuery UI Draggable documentation:

. During drag the element also gets a class of ui-draggable-dragging

You could just write the CSS to leverage this class as opposed to trying to add a class.



回答2:

Same CSS inheritance still applies. If you have your own stylesheet include something like

.ui-draggable-dragging{
    box-shadow:0 0 2px #000;
}

If you do not have a stylesheet. You can still add this inline within your html files using <style> tags



回答3:

I suppose that we add a new class my_class on dargging start, then the code should be like:

$(function () {
    $('ul.sortable div.draggable').draggable({
         start: function( event, ui ) {
              $(this).addClass('my_class'); 
         }
    });
});

css:

.my_class{
/* YOUR CLASS CSS */
}

Refer this JSFIDDLE for adding and removing class on drag start and drag end



回答4:

Try using the option classes: https://api.jqueryui.com/draggable/#option-classes

for example:

$( ".selector" ).draggable({
    classes: {
      "ui-draggable": "move"
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>