Перетаскивающийся блок внутри другого блока


function getCoords(elem) {
    var box = elem.getBoundingClientRect();
    var body = document.body;
    var docEl = document.documentElement;
    var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
    var clientTop = docEl.clientTop || body.clientTop || 0;
    var clientLeft = docEl.clientLeft || body.clientLeft || 0;
    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;
    return { top: Math.round(top), left: Math.round(left) };
        }

var ball = document.getElementById('dragndropblock');
ball.onmousedown = function(e) {
  var coords = getCoords(ball);
  var shiftX = e.pageX - coords.left;
  var shiftY = e.pageY - coords.top;
  ball.style.position = 'absolute';
  document.body.appendChild(ball);
  moveAt(e);
  ball.style.zIndex = 500; // над другими элементами
  function moveAt(e) {
    ball.style.left = e.pageX - shiftX + 'px';
    ball.style.top = e.pageY - shiftY + 'px';
  }
  document.onmousemove = function(e) {
    moveAt(e);
  };
  ball.onmouseup = function() {
    document.onmousemove = null;
    ball.onmouseup = null;
  };
}
ball.ondragstart = function() {
  return false;
};

Пример drag&drop блока:


Комментировать