2016-07-29 124 views
0

我该如何限制“A”可以拖到下面代码中的gameArea div的区域?JQuery可拖拽/捕捉限制区域

我需要添加更多文本才能提交此问题。这够了吗?

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <title>Permutations</title> 
<style> 
    body{ 
     font-family: sans-serif; 
     font-size: 50px; 
     color: green; 
    } 
    #gameArea{ 
     margin:20px auto; 
     width: 600px; 
     height: 400px; 
     border: 4px solid green; 
     background-color: cyan; 
    } 
</style> 
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> 
<script> 
    $(function() { 
     $("#draggable").draggable({ grid: [ 50, 50 ] }); 
    }); 
</script> 
</head> 
<body> 
    <div id="gameArea"> 
     <p id="draggable">A</p> 
    </div> 
</body> 
</html> 

回答

1

嘿检查Demo

$(function() { 
    $("#draggable").draggable({ containment: "parent" , grid: [ 50, 50 ] }); 
}); 

和调整的宽度#draggable div,

#draggable 
{ 
    width:50px; 
    height:50px; 
} 
0

可以使用.droppable()#gameArea来确定丢弃的位置的有效性,就像这样:

$(function() { 
    $("#draggable").draggable({ 
    grid: [ 50, 50 ], 
    revert: "invalid" 
    }); 
    $("#gameArea").droppable({ 
    accepts: "#draggable" 
    }); 
}); 
+0

嘿,他只需要添加容器:{containment:“parent”} – Diptox

+0

是的,很好的解决方案。我已为其+1。这也可以,只要#draggable不是#gameArea – mhodges

+0

的孩子,或者他可以用他希望它作为容器的元素的#ID替换父元素 – Diptox