gpt4 book ai didi

jquery - 限制容器内的可拖动元素

转载 作者:行者123 更新时间:2023-12-01 05:00:53 25 4
gpt4 key购买 nike

我在没有使用 jquery ui 库的情况下制作了一个 div 可拖动,但我想制作可拖动的框,而不是离开其容器。

这是我的 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

最佳答案

只要确保...

  • 盒子的左侧位置大于容器的左侧位置,并且
  • 盒子的右侧位置(左侧位置+盒子宽度)小于容器的右侧位置,并且
  • 盒子的顶部位置大于容器的顶部位置,并且
  • 盒子的底部位置(顶部位置+盒子高度)小于容器的底部位置
<小时/>

http://jsfiddle.net/KdehU/2/

$(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;
});
});

关于jquery - 限制容器内的可拖动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10239014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com