<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>放大镜</title>
<style>
* {
margin: 0;
padding: 0;
}
.small {
width: 130px;
height: 130px;
position: relative;
}
.small .cover {
width: 50px;
height: 50px;
background: orange;
opacity: .3;
position: absolute;
top: 0;
left: 0;
display: none;
}
.big {
width: 308px;
height: 308px;
overflow: hidden;
position: absolute;
top: 0px;
left: 140px;
display: none;
}
.big img {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="small">
<img src="./images/small.jpg" alt="" id="img">
<div class="cover"></div>
</div>
<div class="big">
<img src="./images/big.jpg" alt="" id="pic">
</div>
<script>
var small = document.querySelector('.small');//获取小图片盒子
var cover = document.querySelector('.cover');//获取遮罩层
var img = document.querySelector('#img');//获取小图片
var big = document.querySelector('.big');//获取存放大图片的盒子
var pic = document.querySelector('#pic')//获取大图片
//鼠标移入小图片盒子遮罩层与大图片显示
small.onmouseover = function () {
cover.style.display = 'block';
big.style.display = 'block';
}
//鼠标移出小图片盒子遮罩层与大图片隐藏
small.onmouseout = function () {
cover.style.display = 'none';
big.style.display = 'none';
};
small.onmousemove = function (e) {
var e = e || window.event;
//让鼠标停在遮罩层正中间
var L = e.clientX - cover.offsetWidth / 2;
var T = e.clientY - cover.offsetHeight / 2;
//将遮罩层限制在小图片盒子中
if (L < 0) {
L = 0;
} else if (L > small.offsetWidth - cover.offsetWidth) {
L = small.offsetWidth - cover.offsetWidth;
}
if (T < 0) {
T = 0;
} else if (T > small.offsetHeight - cover.offsetHeight) {
T = small.offsetHeight - cover.offsetHeight
}
// 遮罩层的位置
cover.style.left = L + 'px';
cover.style.top = T + 'px';
//大图与小图的比例
var a = pic.offsetWidth/img.offsetWidth;
var b = pic.offsetHeight/img.offsetHeight;
// 大图移动的距离
pic.style.left = -(L * a) + 'px';
pic.style.top = -(T * b) + 'px';
}
</script>
</body>
</html>
JS实现放大镜效果
最新推荐文章于 2024-07-15 14:11:16 发布