我是一个非常新的编码员,正在学习 javascript 和 jquery 课程。我停下来玩 jquery 中的拖放功能,并被一些东西难住了。
Codepen - http://codepen.io/Allayna-1472610667/pen/ozvqNd
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
div {
margin:auto;
}
#bigsquare {
width: 400px;
height: 400px;
background-color: aqua;
border:2px solid #ccc;
font-weight: bold;
font-size: 20px;
text-align: center;
padding: 0;
}
#smallsquare {
width: 200px;
height: 200px;
background-color: blue;
color: yellow;
font-weight: bold;
text-align: center;
}
</style>
</head>
<body>
<div id="bigsquare">
<p>Drop here</p>
</div>
<div id="smallsquare">
<p>Drop me in the box</p>
</div>
<script type="text/javascript">
var dropped = false;
$("#bigsquare").droppable( {
drop: function(event,ui) {
$("#smallsquare").draggable("option", "containment", "#bigsquare");
$("#smallsquare").css("background-color","green");
$("#smallsquare").html("I am trapped now!");
$("#bigsquare").css("background-color","red");
$("#bigsquare").html("I have you now! BWAH HA HA!");
dropped = true;
}
});
$( "#smallsquare" ).draggable({
drag: function (event, ui) {
if(dropped == false) {
$("#smallsquare").html("Don't let me get trapped!");
}
}
});
</script>
</body>
</html>
这段代码没有任何边距或浮动,它可以完美地工作:小盒子可以自由拖动,直到掉到大盒子里,然后它被困在大盒子里。但是,如果我敢将“margin:auto”应用于我的 div 以使我的 div 居中,那么小盒子就会跳出应该限制它的盒子。