实现jquery放大镜的两种方法

2020-05-27 18:05:58易采站长站整理

jquery写的两种放大镜效果,没有使用到插件。调理和思路清晰。不是使用面向对象方式写的,初学者较容易看懂。废话不多说,看代码。图片这里就不上传了,大家自己找下。最好是找到比例的,这样效果比较好。


<body>
<div id="father">
<div id="container">
<img src="img/400_1.jpg" style="display: block;">
<img src="img/400_2.jpg" >
<div class="shade"></div>
</div>
<div class="small first"><img src="img/50_1.jpg"></div>
<div class="small second"><img src="img/50_2.jpg"></div>
</div>

<div class="big">
<img src="img/800_1.jpg" style="display: block;">
<img src="img/800_2.jpg">
</div>
</body>

css代码


*{padding: 0; margin: 0;}
#father .small{width: 50px; height: 50px; border: 2px solid #ccc; bottom: 0; position: absolute;}
#father .second{left: 70px;}
.third{left: 140px;}
#father{position: relative; top: 100px; left: 50px; height: 460px;}
#container{position: absolute; width: 400px; height: 400px;}
#container img{position: absolute; display: none;}

.shade{width: 200px; height: 200px; position: absolute; background: #000; opacity: 0.4; top: 0;
left: 0; display: none;}
.big{width: 400px; height: 400px; position: absolute; top: 100px; overflow: hidden; left: 500px; display: none;}
.big img{width: 800px; height: 800px; position: absolute; display: none;}

js代码


<script type="text/javascript" src='js/jquery-1.12.4.min.js'></script>
<script type="text/javascript">
$(function () {

changePic('.first',0);
changePic('.second',1);

var shadeWidth = $('.shade').width(),//阴影的宽度
shadeHeight = $('.shade').height(),//阴影的高度
middleWidth = $('#container').width(),//容器的宽度
middleHeight = $('#container').height(),//容器的高度
bigWidth = $('.big').width(),//放大图片盒子的宽度
bigHeight = $('.big').height(),//放大图片盒子的高度
rateX = bigWidth / shadeWidth,//放大区和遮罩层的宽度比例
rateY = bigHeight / shadeHeight;//放大区和遮罩层的高度比例

//当鼠标移入与移出时阴影与放大去显现/消失
$('#container').hover(function() {
$('.shade').show();
$('.big').show();
}, function() {
$('.shade').hide();
$('.big').hide();
}).mousemove(function(e) {//当鼠标移动时,阴影和放大区图片进行移动

//记录下光标距离页面的距离