摘要:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>圖片放大鏡效果</title> <script src="http://code.jquer
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>圖片放大鏡效果</title> <script src="http://code.jquery.com/jquery-3.4.1.min.js"></script> <link href="font-awesome/css/font-awesome.css" rel="stylesheet"> <style> *{margin: 0;padding: 0;} #normal{width: 400px;height: 350px;border: 1px solid #000;position: fixed;top: 20px;left: 20px;} #normal img{width: 100%;height: 100%;} #big-mirror{width: 400px;height: 350px;border: 1px solid #000;position: relative; left: 430px;top: 20px;overflow: hidden;display: none;} #big-mirror>img{position: absolute;width: 1350px;height: 1350px;} #show{width: 80px;height: 80px;display: none;position: absolute;font-size: 80px; text-align: center;line-height: 80px;color: lightcoral; } </style> <script> $(function(){ // $('#big-mirror').hide(); $('#normal').mouseover(function(){ $('#show').show(); $('#big-mirror').show(); $(this).mousemove(function(y){ //console.log(y) // 小方塊跟隨鼠標(biāo)移動(dòng) $('#show').css({ 'left': y.pageX - $('#show').width() / 2, 'top': y.pageY - $('#show').height() / 2, }); }); $('#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)相對(duì)位置 var sx = x - dx; var sy = y - dy; // 獲取小框的寬高 var show_w = $('#show').width() / 2; var show_h = $('#show').height() / 2; // 給入鼠標(biāo)移動(dòng),小框移動(dòng)的距離 $('#show').css({ 'left': sx - show_w + 'px', 'top': sy - show_h + 'px', }); // 控制小框框只能在原圖窗口范圍內(nèi)移動(dòng) // 獲取小框的偏移位置 var lw = $('#show').position().left; var lh = $('#show').position().top; var max_w = $('#normal').width() - $('#show').width(); var max_h = $('#normal').height() - $('#show').height(); // 左邊距 if(lw <= 0){ $('#show').css('left','0px'); } // 右邊距 if(lw >= max_w){ $('#show').css('left', max_w+'px'); } // 上邊距 if(lh <= 0){ $('#show').css('top','0px'); } // 下邊距 if(lh >= max_h){ $('#show').css('top', max_h+'px'); } var lw = $('#show').position().left; var lh = $('#show').position().top; // 鼠標(biāo)在小圖的位置 var new_x = lw * 3; var new_y = lh * 3; $('#big-mirror').find('img').css({ 'left': -new_x + 'px', 'top': -new_y + 'px', }); }); }); $('#normal').mouseleave(function(){ $('#show').hide(); $('#big-mirror').hide(); }); }); </script> </head> <body> <div id="normal"> <img src="images/food.jpg"> <div id="show" class="fa fa-search"></div> </div> <div id="big-mirror"> <img src="images/food.jpg"> </div> </body> </html>
效果圖:
批改老師:天蓬老師批改時(shí)間:2019-05-27 09:21:58
老師總結(jié):放大鏡效果, 在很多網(wǎng)站都有應(yīng)用, 特別是購物類, 體驗(yàn)不錯(cuò)....