// Draggable Inner by Zzbaivong (https://github.com/baivong) function draggableInner(drag, container) { function mouseUp(e) { if (e.which !== 3) return; window.removeEventListener('mousemove', mouseMove, true); drag.style.cursor = 'default'; } function mouseDown(e) { if (e.which !== 3) return; posInDrag = { x: (e.pageX - drag.offsetLeft), y: (e.pageY - drag.offsetTop) }; window.addEventListener('mousemove', mouseMove, true); drag.style.cursor = 'move'; } function mouseMove(e) { if (e.which !== 3) return; posInPage = { x: e.pageX, y: e.pageY }; current = { x: (posInPage.x - posInDrag.x), y: (posInPage.y - posInDrag.y) }; if (current.x < min.x) current.x = min.x; if (current.x > max.x) current.x = max.x; if (current.y < min.y) current.y = min.y; if (current.y > max.y) current.y = max.y; drag.style.left = current.x + 'px'; drag.style.top = current.y + 'px'; } var posInDrag = posInPage = containerSize = dragSize = min = max = current = {}; if (!container) { container = document.body; } containerSize = { w: container.clientWidth, h: container.clientHeight }; dragSize = { w: drag.clientWidth, h: drag.clientHeight }; min = { x: container.offsetLeft, y: container.offsetTop }; max = { x: containerSize.w - dragSize.w + min.x, y: containerSize.h - dragSize.h + min.y }; drag.addEventListener('mousedown', mouseDown, false); window.addEventListener('mouseup', mouseUp, false); drag.oncontextmenu = function(e) { e.preventDefault(); }; } draggableInner(document.getElementById('drag'), document.getElementById('container'));
<div id="container"> <div id="drag"></div> </div>
html, body { margin: 0; padding: 0; } #container { width: 500px; height: 500px; background: #39464E; margin: 10px; overflow: auto; } #drag { position: absolute; width: 400px; height: 300px; background: #FF9800; opacity: 0.7; }