单击黄色div时,我有2个元素。我想将红色方块放在该黄色div中,但要保持在相同的位置(单击黄色元素时,红色不得更改位置)原来是。这只是我做某事的一个示例,两个元素都是位置:绝对,因此应保持这样。有没有办法做到这一点? http://jsfiddle.net/9t6n8dmk/25/
编辑:äs我说我需要两个元素都是绝对的。
<div class="square" id="square">
</div>
<span class="image" id="image">
</span>
.square{
position:absolute;
height:50px;
width:50px;
left:100px;
top:100px;
background:yellow;
}
.image{
position:absolute;
height:50px;
width:50px;
left:100px;
top:10px;
background: red;
}
let square = document.getElementById("square");
let image = document.getElementById("image");
square.addEventListener("mousedown", function(){
square.appendChild(image);
})
答案 0 :(得分:2)
将元素移到另一个父元素时,必须相对于新父元素重新计算元素的位置:
let square = document.getElementById("square");
let image = document.getElementById("image");
square.addEventListener("mousedown", function() {
if (image.parentElement !== square) {
image.style.top = (image.offsetTop - square.offsetTop) + 'px';
image.style.left = (image.offsetLeft - square.offsetLeft) + 'px';
square.appendChild(image);
}
})
.square {
position: absolute;
height: 50px;
width: 50px;
left: 100px;
top: 100px;
background: yellow;
}
.image {
position: absolute;
height: 50px;
width: 50px;
left: 100px;
top: 10px;
background: red;
}
<div class="square" id="square">
</div>
<span class="image" id="image">
</span>