jQuery实现放大镜效果
一、HTML代码
<section>
<div class="top">
<img src="./imgs/0_big.jpg" alt="">
<div class="mask"></div>
</div>
<div class="bottom">
<img src="./imgs/0.jpg" alt="">
<img src="./imgs/1.jpg" alt="">
<img src="./imgs/2.jpg" alt="">
<img src="./imgs/3.jpg" alt="">
<img src="./imgs/4.jpg" alt="">
</div>
<div class="right"> </div>
</section>
二、css代码
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
section {
widows: 430px;
position: relative;
}
.top {
width: 430px;
height: 430px;
position: relative;
margin: 50px 0 30px 50px;
}
.top img {
width: 100%;
}
.top .mask {
width: 125px;
height: 125px;
position: absolute;
top: 0;
left: 0;
z-index: 100;
background: url(./imgs/x.png) repeat;
display: none;
}
.bottom {
margin: 50px 0 0 50px;
}
.bottom img {
width: 80px;
margin-left: 3px;
border: 2px solid transparent;
}
.bottom img:first-child {
border-color: pink;
}
.right {
width: 430px;
height: 430px;
background: url(./imgs/0_big.jpg);
/* 把小块选中的位置放大到整个框 */
/* 因此放大倍数是430/125,所以背景图的大小:430*430/125 */
background-size: 1479.2px;
position: absolute;
top: 0;
left: 480px;
display: none;
}
</style>
三、js代码
<script src="../jquery-3.4.1.js"></script>
<script>
//选中小图,上方切换大图的src
// 记录选中的小图的索引
var eleIndex = 0;
$('.bottom img').mouseenter(function () {
// 在选中图,修改eleIndex之前,eleIndex实际就代表上一次选中图的索引
//把上次选中小图的边框线颜色改为透明色
$(`.bottom img:eq(${eleIndex})`).css('border-color', 'transparent');
// 获取标签的索引值
eleIndex = $(this).index();
$(`.bottom img:eq(${eleIndex})`).css('border-color', 'pink');
// 根据索引修改上方大图的src
var src = `./imgs/${eleIndex}_big.jpg`;
$('.top img').attr('src', src);
$('.right').css('background-image', `url(${src})`);
})
// 遮罩层、右侧大图、显隐操作
$('.top').mouseenter(
function () {
// .add():将找到的标签添加到上一个jQuery对象中
$('.mask').add('.right').show();
// $('.mask').show();
// $('.right').show();
}
);
$('.top').mouseleave(
function () {
$('.mask').add('.right').hide();
}
);
// 监听鼠标移动事件,mask随之移动
$('.top').mousemove(function (event) {
// event默认有,需要用自己添加;z
// jquery绑定事件中,event对象是jquery封装的对象,通过.originalEvent可以获取原生js DOM event对象,从而使用event对象的坐标点
// pageX: 鼠标点距离浏览器可视区域左边界的距离
// offset().left:标签距离浏览器可视区域左边距的距离
var left = event.originalEvent.pageX - $(this).offset().left - 62.5;
var top = event.originalEvent.pageY - $(this).offset().top - 62.5;
// 注意临界范围
// 有效取值范围是[0,315]
if (left < 0) left = 0;
if (left > 305) left = 305;
if (top < 0) top = 0;
if (top > 305) top = 305;
$('.mask').css({
top,
left
})
$('.right').css('background-position', `${-1 * left * 3.44}px ${-1 * top * 3.44}px`);
})
</script>