我想拖动id为id =“dragme”的div我该怎么办呢。如果有可能拖动div dragme不应该超出div名称限制。
<script>
$(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", document.getElementById("dragset"), function (e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
});
</script>
<div id="limits" style="background:#ccc; width:600px; height:600px;">
<div style="background:red; width:200px; height:200px;" id="dragme"></div>
</div>
答案 0 :(得分:1)
最简单的方法是使用jQuery UI draggable的containment
选项:
$(function() {
$("#draggable").draggable({
containment: '#container'
});
});
#container {
height: 300px;
border: 1px solid;
}
#draggable {
width: 150px;
height: 150px;
padding: 0.5em;
}
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div id="container">
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
</div>
答案 1 :(得分:0)
var $dragging = null;
$("#dragme").on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY - 100, //retract here
left: e.pageX - 100 //retract here
});
}
});
$(document.body).on("mousedown", document.getElementById("dragset"), function(e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function(e) {
$dragging = null;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="limits" style="background:#ccc; width:600px; height:600px;">
<div style="background:red; width:200px; height:200px;" id="dragme"></div>
如果您想使用您的代码,只需从偏移量中收回红色框高度和宽度的一半,如下所示:
答案 2 :(得分:0)
使用jQuery Draggable Widget + containment
选项为您的代码提供解决方案:
http://plnkr.co/edit/vqjuQ99YhxQYiiaXjZ32?p=preview
$(function(){
$("#dragme").draggable({
containment: "parent"
});
});