我在不使用jquery ui库的情况下创建了一个div draggable,但是我想制作可拖动的盒子,而不是留下它的容器。
这是我的demo
$(document).ready(function() {
var $dragging = null;
$(document.body).on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY,
left: e.pageX
});
}
});
$(document.body).on("mousedown", ".box", function (e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
});
怎么做?请注意,我没有使用 JQUERY UI 。
答案 0 :(得分:1)
请确保......
$(document).ready(function() {
var $dragging = null;
var container = $('#container'),
c_t = container.offset().top,
c_l = container.offset().left,
c_b = c_t + container.height(),
c_r = c_l + container.width();
$(document.body).on("mousemove", function(e) {
if ($dragging) {
var width = $dragging.width();
var height = $dragging.height();
var new_y = (e.pageY > c_t && (e.pageY + height) < c_b) ? e.pageY : undefined;
var new_x = (e.pageX > c_l && (e.pageX + width) < c_r) ? e.pageX : undefined;
$dragging.offset({
top: new_y,
left: new_x
});
}
});
$(document.body).on("mousedown", ".box", function (e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
});