京东商品页面中的放大镜效果实现
技术::html+ css + js
效果图:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>商品图片放大镜</title>
<style>
* {
padding: 0;
margin: 0;
}
img {
vertical-align: top;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big {
position: absolute;
width: 450px;
height: 450px;
top: 0;
left: 355px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.small {
position: relative;
}
.mask {
width: 100px;
height: 100px;
background-color: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.big img {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box" id="fdj">
<div class="small" id="small">
<img src="images/small.jpg" alt="">
<div class="mask" id="mask"></div>
</div>
<div class="big" id="big">
<img src="images/big.jpg" alt="">
</div>
</div>
</body>
</html>
<script>
var fdj = document.getElementById("fdj");
var small = fdj.children[0];
var big = fdj.children[1];
var mask = document.getElementById("mask");
var bigImg = big.children[0];
small.onmouseover = function () {
big.style.display = "block";
mask.style.display = "block";
}
small.onmouseout = function () {
big.style.display = "none";
mask.style.display = "none";
}
//鼠标在小盒子中移动
var x = 0, y = 0;
small.onmousemove = function (event) {
var event = event || window.event;
x = event.clientX - this.offsetParent.offsetLeft - mask.offsetWidth / 2;
y = event.clientY - this.offsetParent.offsetTop - mask.offsetHeight / 2;
//四个判断放置小黄盒子拖动越界
if (x < 0) {
x = 0;
}
if (x > small.offsetWidth - mask.offsetWidth) {
x = small.offsetWidth - mask.offsetWidth;
}
if (y < 0) {
y = 0;
}
if (y >small.offsetHeight - mask.offsetHeight) {
y = small.offsetHeight - mask.offsetHeight;
}
mask.style.left = x + "px";
mask.style.top = y + "px";
//根据比例移动大盒子的位置,实现放大效果
bigImg.style.left = -x * big.offsetWidth /small.offsetWidth +"px";
bigImg.style.top = -y * big.offsetWidth /small.offsetWidth +"px";
}
</script>
进阶的民工 发布了58 篇原创文章 · 获赞 46 · 访问量 6万+ 私信 关注