我想将一个div从source-parent1移动到target-parent2 唯一的问题是我可以控制父2的div的偏移量 我有这个代码,我发现并试图改变 - 增加了一个10px的偏移量 我无法理解它失败的原因 我似乎无法弄清楚为什么这条线如此重要,它做了什么?
// $("body").prepend($("#block-2").detach());
var velocity = 1500;
$("button").on("click", function(){
var pos = $("#parent-block").offset();
$("body").prepend($("#block-2").detach());
var move = $("#block-2").css({
"position": "absolute",
"z-index": "9999",
"top": pos.top,
"left": pos.left
});
var block1 = $("#block-1").offset();
move.animate({
"top": block1.top + 10,
"left": block1.left + 10
}, velocity, function(){
move.css({"top":"10","left":"10"});
$("#block-1").prepend(move.detach());
});
});
#block-1 {
position: absolute;
border: 1px solid #f00;
width: 150px;
height: 150px;
right: 0;
top: 0;
}
#parent-block {
position: absolute;
border: 1px solid #00f;
width: 150px;
height: 150px;
left: 0;
bottom: 0;
}
#block-2 {
position: absolute;
z-index: 9999;
background-color: #0f0;
width: 50px;
height: 50px;
}
button {
position: absolute;
top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block-1"></div>
<div id="parent-block">
<div id="block-2"></div>
<button>Move block</button>
</div>
http://jsfiddle.net/shantiS2007/taug59wy/?utm_source=website&utm_medium=embed&utm_campaign=taug59wy
答案 0 :(得分:0)
你必须注意css position
。
尝试这个,它的工作!
var velocity = 1500;
$("button").on("click", function() {
var pos = $("#parent-block").offset();
var block2 = $("#block-2").detach();
$("body").prepend(block2);
var move = $("#block-2").css({
"position": "absolute",
"z-index": "9999",
"top": pos.top,
"left": pos.left
});
var velocity = "velocity";
var block1 = $("#block-1").offset();
move.animate({
"top": block1.top + 10,
"left": block1.left + 10
}, velocity, function() {
move.css({
"top": "10",
"left": "10"
});
$("#block-1").prepend(move.detach());
});
});
#block-1 {
position: absolute;
border: 1px solid #f00;
width: 150px;
height: 150px;
}
#block-2 {
position: absolute;
border: 1px solid #f11;
width: 150px;
height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Move block</button>
<div id="block-1">
<p>Block1</p>
</div>
<div id="parent-block">
<div id="block-2">
<p>Block2</p>
</div>
</div>