abstrait:index.html: <!DOCTYPE html> <html lang="en"> <head> <title>仿天貓商品詳情放大鏡效果</title> <link rel="stylesheet" href="static/css/st
index.html: <!DOCTYPE html> <html lang="en"> <head> <title>仿天貓商品詳情放大鏡效果</title> <link rel="stylesheet" href="static/css/style.css"> <script src="static/js/jquery.js"></script> </head> <body> <div id="normal"> <img src="static/images/5.jpg" alt=""> <div id="show"></div> </div> <div id="big"> <img src="static/images/5.jpg" alt=""> </div> <script> $(function(){ $('#big').hide(); // 鼠標(biāo)移上圖片 $('#normal').mouseover(function(){ $('#show').show() $('#big').show(); $(this).mousemove(function(yd){ // 小方塊跟隨鼠標(biāo)移動而移動 $('#show').css( { 'left':yd.pageX-$('#show').width()/2, 'top':yd.pageY-$('#show').height()/2 } ) }) //綁定鼠標(biāo)在normal內(nèi)部移動 $('#normal').mousemove(function(e){ //獲取鼠標(biāo)當(dāng)前的位置 var x = e.clientx; var y = e.clienty; //獲取原圖窗口距離文檔的偏移位置 var dx = $('#normal').offset().left; var dy = $('#normal').offset().top; //計(jì)算鼠標(biāo)的相對位置 var sx = x - dx; var sy = y - dy; //獲取小框的寬高 var mw = $('#show').width()/2; var mh = $('#show').height()/2; //給入鼠標(biāo)移動,小框移動的距離 $('#show').css( { left:sx-mw+'px', top:sy-mh+'px' } ) //控制小框只能在原圖窗口的范圍內(nèi)移動 //獲取小框的偏移位置 var lw = $('#show').position().left; var lh = $('#show').position().top; //獲取x,y軸移動的最大的距離 var maxW = $('#normal').width() - $('#show').width(); var maxH = $('#normal').height() - $('#show').height(); //左邊界 if(lw <= 0){ $('#show').css('left','0px') } //右邊界 if(lw >= maxW){ $('#show').css('left',maxW+'px') } //上邊界 if(lh <= 0){ $('#show').css('top','0px') } //下邊界 if(lh >= maxH){ $('#show').css('top',maxH+'px') } //重新獲取一下小框的偏移位置 var lw = $('#show').position().left; var lh = $('#show').position().top; var newX = lw*3; var newY = lh*3; $('#big').find('img').css({ 'left':-newX+'px', 'top':-newY+'px' }) }) }) // 鼠標(biāo)移出圖片 $('#normal').mouseleave(function(){ $('#show').hide() $('#big').hide(); }) }) </script> </body> </html> style.css: *{ margin: 0px; padding: 0px } /* 展示圖 */ #normal{ width: 450px; height: 450px; border: 1px solid #000; position: fixed; top:20px; left: 20px; } #normal img{ width: 100%; height: 100%; } /* 放大鏡區(qū)域長寬 */ #show{ width: 150px; height: 150px; background: #754930; opacity: 0.4; position: absolute; display: none; } /* 右邊放大鏡長寬 */ #big{ width: 450px; height: 450px; border: 1px solid #000; position: relative; left: 520px; top: 20px; overflow: hidden; } /* 放大鏡內(nèi)部圖片的長寬 */ #big>img{ position: absolute; width: 1350px; height: 1350px; } /* 放大鏡內(nèi)部圖片的長寬/展示圖 = 放大鏡長寬/放大鏡區(qū)域長寬 */ /* 寬度、長度 一定要等比 */
clientX、clientY:
鼠標(biāo)相對于瀏覽器窗口可視區(qū)域的X,Y坐標(biāo)(窗口坐標(biāo)),可視區(qū)域不包括工具欄和滾動條。
pageX、pageY:
類似于event.clientX、event.clientY,但它們使用的是文檔坐標(biāo)而非窗口坐標(biāo),包括滾動條。
offset()設(shè)置或者返回匹配到的元素相對于文檔的偏移。