html:
<div class="sand-content fl"> <img src="images/sand_900x600c.jpg" alt="" id="sandPicture"> </div>
css:
.sand-content { position: relative; width: 600px; height: 400px; overflow: hidden; cursor: move; border: 1px solid #ddd; } .sand-content img {position: relative}
js:
<script> function justifyPicture(child) { let maxLeft = child.offsetParent().outerHeight() - child.outerHeight(); let maxTop = child.offsetParent().outerWidth() - child.outerWidth(); child.css({ left: maxLeft / 2 + 'px', top: maxTop / 2 + 'px' }) } function dragPicture(moveObj) { let maxLeft = moveObj.offsetParent().outerWidth() - moveObj.outerWidth(); let maxTop = moveObj.offsetParent().outerHeight() - moveObj.outerHeight(); moveObj.on('mousedown', event => { let imgTop = parseFloat(moveObj.css('top')); let imgLeft = parseFloat(moveObj.css('left')); let lastPointX = event.clientX; let lastPointY = event.clientY; $(document).on('mousemove', e => { e.preventDefault(); let changeX = e.clientX - lastPointX; let changeY = e.clientY - lastPointY; let disX = imgLeft + changeX; let disY = imgTop + changeY; moveObj.css({ left: Math.max(Math.min(disX, 0), maxLeft) + "px", top: Math.max(Math.min(disY, 0), maxTop) + "px" }) }) }); $(document).on('mouseup', () => { $(document).off('mousemove'); }) } $(document).ready(function () { let child = $('#sandPicture'); justifyPicture(child) dragPicture(child) }) </script>