我有一个脚本要求用户能够在所选图像的顶部放置div。我已经完成了那部分,但我仍然坚持如何获得相对于其父div的可移动div的位置。
我目前的JavaScript:
window.onload = addListeners();
var x_pos = 0,
y_pos = 0;
function addListeners() {
document.getElementById('ClientNametext').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp() {
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e) {
var div = document.getElementById('ClientNametext');
x_pos = e.clientX - div.offsetLeft;
y_pos = e.clientY - div.offsetTop;
window.addEventListener('mousemove', divMove, true);
}
function divMove(e) {
var div = document.getElementById('ClientNametext');
div.style.position = 'absolute';
div.style.top = (e.clientY - y_pos) + 'px';
div.style.left = (e.clientX - x_pos) + 'px';
console.log(div.style.top);
console.log(div.style.left);
}
是否有一种跟踪和捕获可移动div位置并将结果存储在我可以与PHP插入查询一起使用的变量中的方法。
非常感谢你的时间。
答案 0 :(得分:1)
我继续添加了一个新函数updatePos
,它在页面加载和mousemove上调用。
var posX = 0,
posY = 0;
function updatePos() {
var div = document.getElementById('ClientNametext');
var parentPos = div.parentElement.getBoundingClientRect();
var childPos = div.getBoundingClientRect();
var offsets = {
top: childPos.top - parentPos.top,
left: childPos.left - parentPos.left
}
posY = offsets.top;
posX = offsets.left;
document.getElementById("pos").innerHTML = "(" + posX + ", " + posY + ")";
}
updatePos();
function divMove(e) {
var div = document.getElementById('ClientNametext');
div.style.position = 'absolute';
div.style.top = (e.clientY - y_pos) + 'px';
div.style.left = (e.clientX - x_pos) + 'px';
updatePos(); //added this line
}
//your code:
window.onload = addListeners();
var x_pos = 0,
y_pos = 0;
function addListeners() {
document.getElementById('ClientNametext').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp() {
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e) {
var div = document.getElementById('ClientNametext');
x_pos = e.clientX - div.offsetLeft;
y_pos = e.clientY - div.offsetTop;
window.addEventListener('mousemove', divMove, true);
}
#ClientNametext {
width:100px;
height:100px;
background:red;
}
#offset {
position:fixed;
width:200px;
height:200px;
left:90px;
top:80px;
background:blue;
}
<div id="pos"></div>
<div id="offset">
<div id="ClientNametext"> </div>
</div>