Question:
Given a box block box
wide and high, inside which there is a green square 400px
50px
child
, when you click on any area of the parent box
block, the child child
element moves to the clicked place. I got confused in js
code.
let box = document.getElementById('box');
let child = document.getElementById('child');
child.onmousemove = funcMouse;
child.style.top = (event.clientY - 50) + 'px';
child.style.left = (event.clientX - 25) + 'px';
function funcMouse(event) {
this.innerHTML = event.clientX + ' - ' + event.clientY;
}
#box {
position: relative;
width: 400px;
height: 400px;
border: 1px solid black;
}
.child {
position: fixed;
width: 50px;
height: 50px;
background: green;
}
<div id="box">
<div class="child"></div>
</div>
Answer:
$(".box").click(function(e) {
var offset = $(this).position();
var $child = $(this).find(".child");
$child.css({
left: e.clientX - offset.left - $child.width() / 2 + "px",
top: e.clientY - offset.top - $child.height() / 2 + "px"
});
});
.box {
border: 1px solid black;
background-color: lightgreen;
width: 300px;
height: 150px;
overflow: hidden;
}
.child {
border: 1px solid black;
background-color: green;
width: 20px;
height: 20px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="child">
</div>
</div>