как огранчить участок мувабл элемента
доброе времени суток всем!) на стековерфлоу нашёл хороший скрипт для перемещения элементов, как раз то что искал, но не знаю как сделать чтобы невозможно было перемещать элемент за пределы родительского элемента, подскажте пожалуйста :)
var div = document.getElementById('anyDiv'), offX, offY; div.addEventListener('mousedown', mousedown, false); window.addEventListener('mouseup', mouseup, false); function mouseup() { window.removeEventListener('mousemove', move, true); } function mousedown(e) { offY = e.clientY - parseInt(div.offsetTop); offX = e.clientX - parseInt(div.offsetLeft); window.addEventListener('mousemove', move, true); } function move(e) { div.style.top = (e.clientY - offY) + 'px'; div.style.left = (e.clientX - offX) + 'px'; } |
Tecvid, так чтоль?
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title></title> <style> html, body { height: 100%; } body { margin: 0; padding: 0; display: flex; align-items: center; justify-content: center; } .parent { width: 80%; height: 50%; border: 5px solid #cc620c; } .child { width: 100px; height: 100px;; border-radius: 50%; background: orange; cursor: pointer; } </style> </head> <body> <div class="parent"> <div class="child"></div> </div> <script> var parent = document.querySelector('.parent'), child = parent.children[0]; child.onmousedown = function(event) { var childCoords = getCoords(this), parentCoords = getCoords(parent), shiftX = event.pageX - childCoords.left, shiftY = event.pageY - childCoords.top, self = this; this.style.position = 'relative'; document.onmousemove = function(event) { var left = event.pageX - shiftX - parentCoords.left, top = event.pageY - shiftY - parentCoords.top, rightEdge = parent.clientWidth - self.offsetWidth, bottomEdge = parent.clientHeight - self.offsetHeight; left < 0 && (left = 0); left > rightEdge && (left = rightEdge); top < 0 && (top = 0); top > bottomEdge && (top = bottomEdge); self.style.left = left + 'px'; self.style.top = top + 'px'; }; document.onmouseup = function() { document.onmousemove = document.onmouseup = null; }; return false; }; child.ondragstart = function() { return false; }; function getCoords(elem) { var box = elem.getBoundingClientRect(); return { top: box.top + pageYOffset, left: box.left + pageXOffset }; } </script> </body> </html> |
Цитата:
|
Часовой пояс GMT +3, время: 12:26. |