1.js放大镜
应用场景: 商城中的图片展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.small {
width: 400px;
height: 400px;
margin: 50px;
position: relative;
}
.small img {
width: 100%;
}
.big {
width: 600px;
height: 600px;
position: absolute;
top: 0;
left: 410px;
overflow: hidden;
display: none;
}
.big img {
width: 1200px;
position: absolute;
left: 0;
top: 0;
}
.mark {
width: 200px;
height: 200px;
background-color: rgba(0, 0, 0, 0.3);
position: absolute;
top: 0;
left: 0;
display: none;
}
</style>
</head>
<body>
<div class="small">
<img src="./bag.jpg" alt="">
<div class="big">
<img src="./bag.jpg" alt="" class="bigImg">
</div>
<div class="mark"></div>
</div>
<script>
// 获取元素
var small = document.getElementsByClassName("small")[0];
var big = document.getElementsByClassName("big")[0];
var mark = document.getElementsByClassName("mark")[0];
var bigImg = document.getElementsByClassName("bigImg")[0];
// 创建一个比例
var scale;
// 鼠标移入,两个显示,并计算比例
small.onmouseover = function () {
big.style.display = "block";
mark.style.display = "block";
scale = big.offsetWidth / mark.offsetWidth;
}
// 鼠标移出,两个隐藏
small.onmouseout = function () {
big.style.display = "none";
mark.style.display = "none";
}
// 蒙版跟着鼠标动
small.onmousemove = function (e) {
// 蒙版的偏移量 = 鼠标坐标-小盒子偏移量-蒙版宽度一半
mark.style.left = e.pageX - small.offsetLeft - mark.offsetWidth / 2 + "px";
mark.style.top = e.pageY - small.offsetTop - mark.offsetHeight / 2 + "px";
// 做边界判定
if (mark.offsetLeft < 0) {
mark.style.left = 0 + "px";
}
if (mark.offsetLeft > small.offsetWidth - mark.offsetWidth) {
mark.style.left = small.offsetWidth - mark.offsetWidth + "px";
}
if (mark.offsetTop < 0) {
mark.style.top = 0 + "px";
}
if (mark.offsetTop > small.offsetHeight - mark.offsetHeight) {
mark.style.top = small.offsetHeight - mark.offsetHeight + "px";
}
// 图片移动方向和蒙版方向相反
// 图片移动距离 = 蒙版移动距离 * 比例
bigImg.style.left = - mark.offsetLeft * scale + "px";
bigImg.style.top = - mark.offsetTop * scale + "px";
// bigImg.style.left
}
</script>
</body>
</html>