我在div(父级)中有一个div(child)。我将孩子div与margin: auto;
集中在一起。我用containment: "parent"
使用JQuery的可拖动函数使子div可拖动。但是,由于我将边距设置为自动,因此不会让我向左或向右拖动子div。反正是否允许拖拽以避免利润?
HTML:
<div class="parent">
<div class="child"></div>
</div>
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;
}
的Javascript / JQuery的:
$(".child")
.draggable({
containment: "parent",
cursor: "move"
});
这是我的jsfiddle。
我试图在拖动开始时将边距设置为0,但看起来非常难看。这是jsfiddle。
答案 0 :(得分:5)
为了改进Abdul的答案,当你在子框中添加一个边距时,它实际上有一个看不见的边,它填满了孩子左右两边和父母左右两边的空间。所以从技术上来说,你是在移动它,只是它没有空间可以左右移动。
要解决此问题,请移除子项上的边距并使用与垂直居中相同的技术将其水平居中:
top: 50%;
left: 50%;
transform: translateY(-50%) translateX(-50%);
答案 1 :(得分:0)
我会回答你的问题,让它按你想要的方式运作。但我不知道你做的是好还是坏。这是一个更新的小提琴http://jsfiddle.net/hLdrxybm/2/
只需从子项中删除margin
即可添加left
属性,以便块看起来居中。还有其他方法可以使div居中,但我不确定这会有什么好处,因为你想要可拖动的元素