javascript - 如何使用 JqueryUI sortable 更改放置元素的样式?

标签 javascript jquery html css jquery-ui

我有一个非常简单的网站,我希望能够在其中的两个 DIV 容器之间拖放一些样式化的 DIV 元素。我已经使用 JQueryUI 的可排序功能成功地实现了拖放行为,如下所示:

$("#active-container").sortable({connectWith: "#inactive-container"});
$("#inactive-container").sortable({connectWith: "#active-container"});

我使用此方法在单击按钮时将我的可放置 DIV 元素添加到容器中:

function createDeviceDiv (deviceObject, className){

  var div = document.createElement('div');

  div.id = deviceObject.deviceId;

  div.className = className + ' draggable="true"';

  div.textContent = deviceObject.deviceName;

  return div;
}

我的 CSS 看起来像这样:

.active-device-element
{
  width: 200px;
  height: 40px;
  border: 2px solid #666666;
  margin: 10px;
  background-color: lightgreen;
  cursor: move;
  border-radius: 25px;
  text-align: center;
  vertical-align: middle;
  line-height: 35px; 
  -webkit-user-select: none; 
}

.inactive-device-element
{
  width: 200px;
  height: 40px;
  margin: 10px;
  border: 2px solid #666666;
  background-color: floralwhite;
  cursor: move;
  border-radius: 25px;
  text-align: center;
  vertical-align: middle;
  line-height: 35px; 
  -webkit-user-select: none; 
}

#active-container, #inactive-container
{
  background-color: lightgrey;
  min-height: 100px;
}

我的 index.html 页面(使用 Twitter bootstrap 3)的相关部分如下:

<div class="row">
    <div class="col-xs-6">
        <h2>Active Devices</h2>
        <p>The following devices are currently listed as active.</p>
        <div id="active-container">
        </div>
    </div>
    <div class="col-xs-6">
        <h2>Inactive Devices</h2>
        <p>The following devices are currently listed as inactive.</p>
        <div id="inactive-container">
        </div>
    </div>
</div>

因此,在两个容器之间拖放效果很好。但是,当放下时,该元素会保留原始样式。我需要突出显示通过更改已被拖放到不同背景颜色/样式的任何元素所做的更改,因此基于我的 CSS,类似于“.modified-device-element”。我不清楚实现此目标的最佳方法是什么。

非常感谢任何帮助。

最佳答案

jQuery UI Sortable 有几个您可以使用的事件,其中之一是 receive .您可以设置事件监听器以获取两个容器的更新。然后,当元素从一个容器移动到另一个容器时,您可以获取该元素并根据需要对其进行修改,包括添加另一个类。

$('#active-container, #inactive-container').on('sortreceive', function(event, ui) {
    ui.item.addClass('modified-device-element');
});

或在设置小部件时

$('#active-container').sortable({
    receive: function(event, ui) {
        ui.item.addClass('modified-device-element');
    }
});

$('#inactive-container').sortable({
    receive: function(event, ui) {
        ui.item.addClass('modified-device-element');
    }
});

关于javascript - 如何使用 JqueryUI sortable 更改放置元素的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26269357/

相关文章:

jquery - 在 JQuery 中获取 Richfaces 日历的选定日期

jquery - 从其他函数访问变量

javascript - 鼠标单击无法提供坐标

javascript - 如何使用httpresponse将html中的值返回到android java类中

javascript - 尝试将服务注入(inject)组件

javascript - 在 Javascript 中仅显示浏览器版本

javascript - 使用 Bootstrap 展开全部和折叠所有按钮

html - <applet height ="100%"> 在 IE 中导致垂直滚动条。为什么/如何避免?

javascript - 即使元素的值也在 CSS 中设置,也获取内联样式值?

javascript - Vue 和 firestore 数据绑定(bind)