abstract:html代码<div id="normal"> <img src="static/images/fan.jpg" alt=""> <div id="show&quo
html代码
<div id="normal"> <img src="static/images/fan.jpg" alt=""> <div id="show"></div> </div> <div id="big"> <img src="static/images/fan.jpg" alt=""> </div>
css代码
<style type="text/css"> *{margin:0;padding: 0;} #normal{width: 450px;height: 450px;border:1px solid #000000;position: fixed;top:20px;left:20px;} #normal img{width: 100%;height: 100%;} #show{width:150px;height:150px;background: #000000;opacity: 0.2;position: absolute;display: none;} #big{width:450px;height: 450px;border:1px solid #000000;position: relative;top:20px;left:490px;overflow: hidden;display: none;} #big img{width: 1350px;height: 1350px;position: absolute;} </style>
js代码
<script type="text/javascript"> $(function(){ $('#normal').mouseover(function(){ $('#show').show(); $('#big').show(); $(this).mousemove(function(yd){ //获取鼠标的当前位置 var mx = yd.pageX; var my = yd.pageY; //获取原图窗口距离文档的偏移位置 var ox = $('#normal').offset().top; var oy = $('#normal').offset().left; //计算鼠标的相对位置 var mpx = mx-ox; var mpy = my-oy; //给入小框的移动距离 $('#show').css({ 'left':mpx-$('#show').width()/2+'px', 'top':mpy-$('#show').height()/2+'px' }); //获取小框相对于父元素的偏移位置 var showOffsetX = $('#show').position().left; var showOffsetY = $('#show').position().top; //console.log(mx+'~'+ox+'~'+showOffsetX); //计算小框的最大偏移位置 var maxOffsetX = $(this).width()-$('#show').width(); var maxOffsetY = $(this).height()-$('#show').height(); //左 if(showOffsetX<=0){ $('#show').css('left','0px'); } //右 if(showOffsetX>=maxOffsetX){ $('#show').css('left',maxOffsetX+'px'); } //上 if(showOffsetY<=0){ $('#show').css('top','0px'); } //下 if(showOffsetY>=maxOffsetY){ $('#show').css('top',maxOffsetY+'px'); } //获取小框重新计算后相对于父元素的偏移位置 showOffsetX = $('#show').position().left; showOffsetY = $('#show').position().top; $('#big').find('img').css({ left:-showOffsetX*3+'px', top:-showOffsetY*3+'px' }); }); }); $('#normal').mouseout(function(){ $('#show').hide(); $('#big').hide(); }); }) </script>
放大镜图片的宽高/展示图片的宽高 = 放大镜的宽高/放大镜区域的宽高
效果图
Correcting teacher:韦小宝Correction time:2018-12-11 09:11:13
Teacher's summary:恩!写的很不错!这个效果在各种商城项目中使用的最为频繁!课后还要记得多多练习啊!