我在div(父母)中有一个div(孩子).我把孩子的中心放在了一起margin: auto;.我containment: "parent"使用JQuery的可拖动功能使子div可拖动.但是,由于我将边距设置为自动,因此不会让我向左或向右拖动子div.反正是否允许拖拽以避免利润?
HTML:
<div class="parent">
<div class="child"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
.parent {
background-color: orange;
position: relative;
left: 0px;
top: 0px;
height : 300px;
width: 300px;
}
.child {
background-color: green;
position: relative;
height : 100px;
width: 100px;
top: 50%;
transform: translateY(-50%);
margin: auto;
}
Run Code Online (Sandbox Code Playgroud)
使用Javascript/JQuery的:
$(".child")
.draggable({
containment: "parent",
cursor: "move"
});
Run Code Online (Sandbox Code Playgroud)
这是我的jsfiddle.
我试图在拖动开始时将边距设置为0但看起来很丑陋.这是jsfiddle.
为了改进Abdul的答案,当你在子框中添加一个边距时,它实际上有一个看不见的边,填补了孩子左右两侧和父母左右两边之间的空间.所以从技术上讲,你是在移动它,只是它没有空间可以左右移动.
要解决此问题,请移除子项上的边距并使用与垂直居中相同的技术将其水平居中:
top: 50%;
left: 50%;
transform: translateY(-50%) translateX(-50%);
Run Code Online (Sandbox Code Playgroud)