我创建了一个网格,每个列都有一个数字签名。我想要一个拖放的div,可以抓取到每个列的边框,然后基本上显示从我的div被剪贴到的最外层的列的范围。
示例如下:https://jsfiddle.net/Cataras/dpdLLcft/
$(function() {
$(".draggable").draggable({
snap: ".hour-full, .hour-half",
snapMode: 'both',
stop: function(event, ui) {
/* Get the possible snap targets: */
var snapped = $(this).data('ui-draggable').snapElements;
/* Pull out only the snap targets that are "snapping": */
var snappedTo = $.map(snapped, function(element) {
return element.snapping ? element.item : null;
});
/* Display the results: */
var result = '';
$.each(snappedTo, function(idx, item) {
result += $(item).text() + ", ";
});
$("#results").html("Snapped to: " + (result === '' ? "Nothing!" : result));
}
});
});取自此问题的代码:How to find out about the "snapped to" element for jQuery UI draggable elements on snap
但是,它不仅在div的左侧和右侧显示列号,而且显示介于中间的所有列。有时,右边的也是红色条形的,显然是不动的。有什么建议吗?
发布于 2016-06-03 17:54:34
snappedTo数组有点贪婪,我将使用left定位来确定所拖动的项目本质上是over。
下面是一个有用的示例:https://jsfiddle.net/Twisty/dpdLLcft/5/
jQuery
$(function() {
$(".draggable").draggable({
snap: ".hour-full, .hour-half",
snapMode: 'both',
stop: function(event, ui) {
console.log("Drag stopped at Left: " + ui.offset.left);
/* Get the possible snap targets: */
var snapped = $(this).data('ui-draggable').snapElements;
console.log($(this).data('ui-draggable'));
/* Pull out only the snap targets that are "snapping": */
var snappedTo = $.map(snapped, function(element) {
if (element.snapping) {
console.log("Found snapped element: " + $(element.item).text() + ". Left: " + element.left + " Width: " + element.width);
return element;
}
});
/* Display the results: */
var result = '';
$.each(snappedTo, function(idx, item) {
if (ui.offset.left == item.left) {
console.log(item);
result = $(item.item).text() + ", ";
result += $(snappedTo[idx + 3].item).text();
}
});
$("#results").html("Snapped to: " + (result === '' ? "Nothing!" : result));
}
});
});首先,使用循环,我从以snapping作为true的元素中获取所有数据。
其次,我们循环遍历这些元素,并比较可拖的元素的左侧边缘和不同的元素。我们在控制台中看到了这一点:
Drag stopped at Left: 48
Found snapped element. Left: 28 Width: 20
Found snapped element. Left: 48 Width: 20
Found snapped element. Left: 68 Width: 20
Found snapped element. Left: 88 Width: 20
Found snapped element. Left: 108 Width: 20
Found snapped element. Left: 128 Width: 20然后,我们可以比较这一点,并确定我们从哪个元素开始。
if (ui.offset.left == item.left) 当左偏移量为48,元素左侧为48 (48 == 48)时,我们将更新结果:
result = item.item.innerHTML + ", ";
result += snappedTo[idx + 3].item.innerHTML;因为我们知道可拖放的列的数量,并且我们知道开始,所以我们只是通过增加索引从另一个元素中得到信息。
Snapped to: 2, 5我想这就是你从描述中想要达到的目的。如果要获得外部索引,只需简单地调整索引:
result = snappedTo[idx - 1].item.innerHTML + ", ";
result += snappedTo[idx + 4].item.innerHTML;这应该是你想要的你想要的方式。如果你有问题请告诉我。
https://stackoverflow.com/questions/37591118
复制相似问题