问题是:当设置grid 和containment 选项时,拖动事件出现问题。 有些物体(根据它们的起始位置)不能完全接近容器的边缘。有办法解决这个问题吗? (不改变事件拖动?)
html
<div id="container">
<div id="obj1"></div>
<div id="obj2"></div>
</div>
js
$("#obj1,#obj2").draggable({
containment : "parent",
grid : [3,3]
});
CSS
#container{
width:400px;
height:400px;
border:1px solid red;
}
#obj1{
position:absolute;
width:53px;
height:53px;
background:blue;
left:27px;
top:27px;
}
#obj2{
position:absolute;
width:53px;
height:53px;
background:red;
left:53px;
top:103px;
}
Example on JSFiddle (obj1 可以,obj2(在这种情况下)不行)
最佳答案
您已将网格设置为 [3, 3],这意味着 jQuery 将增加/减少对象的位置 3 个像素。所以如果你想让对象能够到达[0, 0],你需要对齐网格上的起始位置:
#obj2{
position:absolute;
width:53px;
height:53px;
background:red;
left:54px;
top:105px;
}
参见 http://jsfiddle.net/9oLtt9uy/2/
更新
如果您的起始坐标是可变的,您应该动态调整它们,以便它们对齐,例如:
var gridSpacing = 10,
gridSize = $("#obj1").width();
// make sure the grid is big enough to fit an exact number of objects
$("#container").width(gridSpacing * gridSize + 2);
$("#container").height(gridSpacing * gridSize + 2);
// align each object and make it draggable
$("#obj1,#obj2").each(function() {
$(this).css({
"left": ($(this).position().left - ($(this).position().left % gridSpacing) - 1),
"top": ($(this).position().top - ($(this).position().top % gridSpacing) - 1)
});
$(this).draggable({
containment : "parent",
grid : [gridSpacing,gridSpacing]
});
});
关于javascript - jQueryUI Draggable - 网格和包含选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27431867/