<!doctype html> <html> <head> <meta charset="utf-8"> <title>类似放大镜</title> <script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <style> .crop-box,.preview-box { display:inline-block; vertical-align:top; } .crop,.preview { position:relative; overflow:hidden; } .crop-area,.preview { width:80px; height:80px; } .crop-area { position:absolute; left:88px; top:56px; outline:256px solid #000; outline:256px solid rgba(0,0,0,.5); background:url(about:blank); background:linear-gradient(to top,transparent,transparent); filter:alpha(opacity=50); cursor:move; } :root .crop-area { filter:none; } .crop img,.preview img { display:block; width:256px; height:192px; } .preview img { position:absolute; left:-88px; top:-56px; } </style> </head> <body> <div class="crop-box"> <h4>剪裁(仅演示移动)</h4> <div class="crop"> <div id="cropArea" class="crop-area"></div> <img src="http://www.jq22.com/img/cs/500x500-9.png"> </div> </div> <div class="preview-box"> <h4>预览</h4> <div class="preview"> <img id="previewImg" src="http://www.jq22.com/img/cs/500x500-9.png"> </div> </div> <script> var elCropArea = $('#cropArea'); var elPreviewImg = $('#previewImg'); var data = {}; elCropArea.on('mousedown', function(event) { data = { moving: true, left: elCropArea.position().left, top: elCropArea.position().top, x: event.pageX, y: event.pageY }; }); $(document).on({ mousemove: function(event) { if (data.moving) { event.preventDefault(); // 移动距离 var moveX = event.pageX - data.x; var moveY = event.pageY - data.y; // 目标坐标 var left = data.left + moveX; var top = data.top + moveY; // 边界判断 if (left < 0) { left = 0; } else if (left + 80 > 256) { left = 176; } if (top < 0) { top = 0; } else if (top + 80 > 192) { top = 112; } // 重定位 elCropArea.css({ left: left, top: top }); elPreviewImg.css({ left: -1 * left, top: -1 * top }); } }, mouseup: function() { data.moving = false; } }); </script> </body> </html>