몇 가지 간단한 끌어서 놓기를 만들었습니다. (유용하게 사용될한다고처럼 보인다 코드의 일부 정크 있습니다.)어떻게 전역 좌표를 로컬 좌표로 변환합니까?
HTML :
<div id="container">
<div id="target"></div>
</div>
자바 스크립트 :
var el = document.getElementById('target');
var mover = false,
x, y, posx, posy, first = true;
el.onmousedown = function() {
mover = true;
};
document.onmouseup = function() {
mover = false;
first = false;
};
document.onmousemove = function (e) {
if (mover) {
e = e || window.event;
var target = e.srcElement || e.target;
var rect = target.getBoundingClientRect();
if (first) {
first = false;
x = (getMouseCoordinates(e).x - rect.left);
y = (getMouseCoordinates(e).y - rect.top);
}
posx = getMouseCoordinates(e).x;// - x;
posy = getMouseCoordinates(e).y;// - y;
el.style.left = posx + 'px';
el.style.top = posy + 'px';
}
};
function getMouseCoordinates(e) {
e = e || window.event;
var pageX = e.pageX;
var pageY = e.pageY;
if (pageX === undefined) {
pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return {
x: pageX,
y: pageY
}
}
CSS :
#target {
left: 50px;
top: 50px;
width: 150px;
height: 100px;
background-color: #ffc;
position: absolute;
}
#container {
left: 30px;
top:30px;
width: 300px;
height: 300px;
background-color: red;
position: absolute;
}
문제는 드래그 가능한 컨테이너 내부에 드래그 가능한 것입니다. 따라서 마우스의 전역 좌표로 draggable을 배치하면 draggable은 실제로 전역 컨테이너가 아닌 위치에 상대적으로 배치됩니다.
그럼 어떻게하면 draggable이 뛰어 오르지 않도록 좌표를 변환 할 수 있습니까? 확실히 부모 컨테이너의 오프셋을 알아야합니까?
'getBoundingClientRect()'를 사용하면 컨테이너 요소의 오프셋 위치를 가져올 수 있습니다. 이미 코드를 사용하여 드래그 가능한 요소의 오프셋 위치를 얻습니다. –
그렇게 생각합니다. 상위 요소를 가져 오는 것이 브라우저 간 의존성이 있는지 궁금합니다. 내 생각은이 모든 것을 함께 피하고 draggable을 루트에 복제하고 대신 드래그하는 것입니다. –
jquery를 사용하면 'offset()'메서드는 문서에 상대적인 요소의 왼쪽과 맨을 반환합니다. –