如何在拖动时更改可排序元素的样式?

6

这是我的脚本:

<script>
    $(function() {
    t1 = window.performance.now()
    var $sortable1 = $( "#dragableElement" ).sortable({
      connectWith: ".connectedSortable",
      items: ".sorting-initialize",
      containment: "window"

    });
    $sortable1.find(".ui-state-default").one("mouseenter",function(){
        $(this).addClass("sorting-initialize");
        $sortable1.sortable('refresh');

    });

    t2 = window.performance.now()
    console.log(t2-t1)
  });
  </script>

这个脚本可以改变被拖动项目的样式吗?例如添加背景:'黄色',可以改变颜色等等?
2个回答

8

您还可以使用jQueryUi sortable事件start来实现此操作,请尝试以下内容:

 $( "#dragableElement" ).sortable({
    connectWith: ".connectedSortable",
    items: ".sorting-initialize",
    containment: "window",
    start: function( event, ui ) { 
      $(ui.item).addClass("yellow");
    },
    stop:function( event, ui ) { 
      $(ui.item).removeClass("yellow");
    }
});

Demo


当我在我的代码中添加了这些启动和停止函数时,拖放功能消失了。有什么想法为什么会这样?当我注释掉这些行时,一切都很好。 - Titas Kurtinaitis
请确保在 containment: "window" 后面加上逗号 ,,正确写为 containment: "window", - Umesh Sehta
是的,我在"window"后面错过了“逗号”,但是无论选择哪种颜色,使用拖放样式时样式都不会改变。 - Titas Kurtinaitis
你在 CSS 中添加了 yellow 类吗? - Umesh Sehta
.yellow { background:yellow; } - Umesh Sehta

5
当您对项目进行排序时,会向项目添加一个类 ui-sortable-helper。您可以使用这个类来更改正在排序的项目的外观。然后,您可以使用 CSS 规则来修改此项目的外观。但是,您必须确保您的 CSS 覆盖 jQuery UI 的默认 CSS。为此,您可能需要具有非常特定的选择器。
示例:http://jsfiddle.net/UAcC7/1503/ CSS:
.ui-sortable-helper {
    background:green;
}

HTML:

<div class="demo">
        <ul id="sortable">
            <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
            <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
            <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 7</li>
        </ul>
    </div>
    <!-- End demo -->
    <div class="demo-description" style="display: none; ">
        <p>Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share <code>draggable</code> properties.</p>
    </div>
    <!-- End demo-description -->

JS:

$("#sortable").sortable();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接