我试图阻止可拖动的div超出容器div。
这是FIDDLE进一步解释这个问题。
我在我的代码中尝试过类似的东西,但这会阻止我的代码工作:
if($('#set').offset().left > 50)
{
$( '#set div' ).draggable( 'option', 'revert', true ).trigger( 'mouseup' );
}
有人可以就此问题提出建议吗?
答案 0 :(得分:1)
使用选项
containment: "parent" // Or any selector; "parent" refers to the immediate parent
http://api.jqueryui.com/draggable/#option-containment
像:
$( '#set div' ).draggable({
revert : true,
containment: "parent"
}).trigger( 'mouseup' );
答案 1 :(得分:1)
我已经改变了这个
<div id="set1">
<div id='set'>
<div data-need="1"></div>
<div data-need="2"></div>
<div data-need="3"></div>
<div data-need="4"></div>
<div data-need="5"></div>
</div>
</div>
并在js containment: "#set1 div",
$(function() {
$( "#set div" ).draggable({
containment: "#set1 div",
stack: "#set div",
stop: function(event, ui) {
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
var need = ui.helper.data("need");
console.log(pos_x);
console.log(pos_y);
console.log(need);
//alert( pos_x);
//Do the ajax call to the server
$.ajax({
type: "POST",
url: "your_php_script.php",
data: { x: pos_x, y: pos_y, need_id: need}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
这可以按照您的要求运作