我想在拖动一个对象并悬停可放置对象时添加可放置事件侦听器。
这是我的代码:
$('.will-be-drag').draggable({
helper: 'clone',
drag: function (event, ui) {
$('.will-be-drop').hover(function () {
$(this).droppable({
drop: function (event, ui) {
let item = ui.draggable;
console.log(item[0])
item.detach().appendTo($(this));
}
});
}, function () {
$(this).droppable('disable');
});
}
});
我的HTML就是这样:
<div class="will-be-drag"></div>
<div class="will-be-drag"></div>
<div class="will-be-drag"></div>
<?php
for($i = 0; $i <= 3000; $i++){
?>
<div class="will-be-drop"></div>
<?php
}
?>
由于性能问题,我这样做。我有3k的可放置对象,拖动时冻结。它必须仅通过拖动droppable
对象并悬停$('.will-be-drag')
来添加$('.will-be-drop')
事件监听器。
使用此代码,仅在悬停时添加,而在拖动时不添加。
我该怎么办?
我想让javascript喘口气,设置3k可放置对象时已经晚了。只有30-40个可拖动元素。这是一张桌子。
会建议这个:
$(function() {
function makeDrops(n) {
var t = $(".ui-widget").eq(1);
for (var i = 1; i <= n; i++) {
$("<div>", {
id: "drop-" + i,
class: "will-be-drop ui-widget-content"
}).appendTo(t);
}
}
makeDrops(3000);
$('.will-be-drag').draggable({
helper: 'clone',
start: function() {
$(".will-be-drop").droppable("enable");
},
stop: function() {
$(".will-be-drop").droppable("disable");
$(".will-be-drop.ui-state-highlight").removeClass("ui-state-highlight");
}
});
$(".will-be-drop").droppable({
drop: function(event, ui) {
let item = ui.draggable;
console.log("Drag Item " + item.text().trim() + " dropped to " + $(this).attr("id"));
item.detach().appendTo($(this));
},
over: function() {
$(this).addClass("ui-state-highlight");
},
out: function() {
$(this).removeClass("ui-state-highlight");
}
}).droppable("disable");
});
.will-be-drag {
width: 50px;
height: 50px;
padding: 0.25em;
float: left;
margin: 10px 10px 10px 0;
}
.will-be-drop {
width: 100px;
height: 100px;
padding: 0.25em;
float: left;
margin: 10px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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>
<div class="ui-widget">
<div class="will-be-drag ui-widget-content">A</div>
<div class="will-be-drag ui-widget-content">B</div>
<div class="will-be-drag ui-widget-content">C</div>
</div>
<div class="ui-widget">
</div>