偏移正在返回之前的位置(在被排序之前)--JQuery UI。

问题描述 投票:0回答:1

请看。https:/simplexshotz.github.ioSorting-Dropping。

当您将一个可排序项拖动到另一个可排序项上时(使它们互换位置),偏移位置(元素.offsetTop、元素.offsetLeft)不会更新。

上述示例的工作方式如下:如果您将一个可排序项放到另一个可排序项上,将显示一个警报,告诉您将它放到了哪个可排序项上。如果当您将其丢弃时,光标不在另一个可排序项上,则不会显示警报。

唯一的问题是,当您将其放下时,是否在某个可分类项上,是基于该可分类项的原始位置。如果您将一个可排序项拖过另一个(使它们互换位置),然后将其放置在可排序项互换位置之前的位置,警报仍然会出现。这让我相信,偏移使用的是之前的位置。

var order = [];

function setup() {
  // Add the sortables:
  for (var i = 0; i < 5; i++) {
    document.getElementById("container").innerHTML += "<div class='sortable' id='sortable-" + i + "'>Sortable " + i + "</div>";
    order.push(i);
  }
  // Make them actually sortable:
  $("#container").sortable({
    stop: function(e, ui) {
      // Detect drop over another sortable:
      var s = document.getElementById("container").childNodes;
      var c = Number(ui.item[0].id.split("-")[1]); // this is the index of the sortable that was being moved
      for (var i = 0; i < s.length; i++) {
        if (order[i] !== c) { // Make sure it's not checking if the cursor is over itself
          // Basic pixel -> rectangle collisions:
          if (e.clientX >= s[i].offsetLeft && e.clientY >= s[i].offsetTop && e.clientX <= s[i].offsetLeft + s[i].offsetWidth && e.clientY <= s[i].offsetTop + s[i].offsetHeight) {
            console.log("Sortable dropped over sortable " + order[i]);
            break;
          }
        }
      }
      // Re-order them:
      for (var i = 0; i < s.length; i++) {
        order[i] = Number(s[i].id.split("-")[1]);
      }
    }
  });
}
setup();
* {
  font-family: Helvetica;
}

body {
  background-color: rgb(255, 255, 255);
  padding: 0px;
  margin: 0px;
}

#container {
  border: 1px solid rgb(200, 200, 200);
  border-radius: 10px;
  padding: 20px;
  margin: 50px 25% 0px 25%;
}

.sortable {
  border-radius: 10px;
  background-color: rgb(50, 50, 50);
  color: rgb(255, 255, 255);
  padding: 10px;
  width: calc(100% - 20px);
  margin-bottom: 10px;
}
<!DOCTYPE html>
<html>

<head>
  <title>Example</title>
  <!-- JQuery -->
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>

<body>
  <div id="content">
    <div id="container"></div>
  </div>
</body>

</html>

对不起,如果这有点复杂,我不知道如何解释。

任何帮助都是感激的。先谢谢你了。

javascript jquery offset cursor-position
1个回答
0
投票

这不是偏移的问题。它没有按照你的期望工作,因为 order[i] !== c 并不是排除光标在你刚刚移动的元素的最终位置上,而是排除光标在你刚刚移动的元素的起始(前)位置上。

© www.soinside.com 2019 - 2024. All rights reserved.