我是一个非常新的程序员,经历了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居中,那么这个小盒子就跳出了应该限制它的盒子。