相对拖放位置

时间:2016-01-21 19:05:32

标签: javascript

为什么当按下鼠标弹跳时球相对定位?绝对定位是指不会发生这种情况。

var ball = document.querySelector('.ball');

ball.onmousedown = function(event) {
  var shiftX = event.pageX - getCoords(this).left,
      shiftY = event.pageY - getCoords(this).top;

  this.style.position = 'relative';
  this.zIndex = 10000;

  function move(event) {
    this.style.left = event.pageX - shiftX + 'px';
    this.style.top = event.pageY - shiftY + 'px';
  }

  move.call(this, event);

  document.onmousemove = function(event) {
    move.call(ball, event);
  };

  this.onmouseup = function(event) {
    document.onmousemove = this.onmouseup = null;
  };
  
  return false;
};

ball.ondragstart = function() {
  return false;
};

function getCoords(elem) {
  var box = elem.getBoundingClientRect();

  return {
    top: box.top + window.pageYOffset,
    left: box.left + window.pageXOffset
  };
}
body {
  margin: 50px;
}

img {
  cursor: pointer;
}
<img class="ball" src="https://js.cx/clipart/ball.svg" alt="" />

我想这是因为身体元素的填充。请解释一下。

1 个答案:

答案 0 :(得分:0)

似乎我找到了答案 Implementing drag and drop on relatively positioned elements in JavaScript

并且如上所述,在相对位置,您的元素包含其父标记中所有对象的偏移量 和父母的保证金填充 因此,当您尝试获得elemtn的位置时,您应该计算它在父级中的实际偏移量,请参阅我的代码示例使用 count index

&#13;
&#13;
<html>

<body>


<div id=obj1 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<div id=obj2 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<div id=obj3 style="width:100px; height:100px; background:#000; position:relative; " ></div>

<script>

var dragObj, count=0;

function set_drag_drop(obj)
{
	if(count>0){
		// count margins and divs offset
		// body{ margin:10px; }
		// height:100px;
		obj.adx = 10; 
		obj.ady = 10 + (count*100)
	}else{
		obj.adx = 0;
		obj.ady = 0;
	}
	count++;
	
	obj.onmousedown = function(e)
	{
		var rect = obj.getBoundingClientRect();
		obj.dx = rect.left - e.clientX;
		obj.dy = rect.top - e.clientY;
		obj.isDown = true;
		dragObj = this;
	}

	obj.onmouseup = function(e)
	{
		obj.isDown = false;
	}

	document.onmousemove = function(e)
	{
		if(dragObj && dragObj.isDown)
		{
			dragObj.style.left = e.pageX -dragObj.adx+ dragObj.dx +"px";
			dragObj.style.top = e.pageY -dragObj.ady+ dragObj.dy + "px";
		}
	}
}

set_drag_drop(document.getElementById("obj1"));
set_drag_drop(document.getElementById("obj2"));
set_drag_drop(document.getElementById("obj3"));

</script>
</html>
&#13;
&#13;
&#13;