js实现淘宝京东等购物网站中商品图片放大的效果
例子如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>图片放大效果</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big {
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.mask {
width: 175px;
height: 175px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0px;
left: 0px;
cursor: move;
display: none;
}
.small {
position: relative;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="small"><!--小层-->
<img src="images/small.png" width="350" alt=""/>
<div class="mask"></div><!--遮挡层-->
</div><!--小图-->
<div class="big"><!--大层-->
<img src="images/big.jpg" width="800" alt=""/><!--大图-->
</div><!--大图-->
</div>
<!--导入外部的js文件-->
<script>
//根据id获取元素对象
function my$(id) {
return document.getElementById(id);
}
//get the elements needed
var box = my$("box");
var small = box.children[0];
var mask = small.children[1];
var big = box.children[1];
var bigImg = big.children[0];
//register mouseover event
small.onmouseover = function () {
mask.style.display = "block";
big.style.display = "block";
}
//register mouseleave event
small.onmouseleave = function () {
mask.style.display = "none";
big.style.display = "none";
}
//register the mousemove event
small.onmousemove = function (e) {
// get the position
var x = e.clientX;
var y = e.clientY;
//solve the problem of margin
x = x - 100;
y = y - 100;
//make the mouse is in the center of mask
x = x - mask.offsetWidth / 2;
y = y - mask.offsetHeight / 2;
//the minimum position of mask
x = x < 0 ? 0 : x;
y = y < 0 ? 0 : y;
//the maximum position of mask
x = x > small.offsetWidth - mask.offsetWidth ? small.offsetWidth - mask.offsetWidth : x;
y = y > small.offsetHeight - mask.offsetHeight ? small.offsetHeight - mask.offsetHeight : y;
//set the position of mask
mask.style.left = x + "px";
mask.style.top = y + "px";
//遮挡层的移动距离/大图的移动距离=遮挡层的最大移动距离/大图的最大移动距离
//大图的移动距离=遮挡层的移动距离*大图的最大移动距离/遮挡层的最大移动距离
//大图的横向的最大移动距离
var maxX = bigImg.offsetWidth-big.offsetWidth;
//大图的纵向的最大移动距离
var maxY = bigImg.offsetHeight-big.offsetHeight;
//大图的横向移动的坐标
var bigImgMoveX = x*maxX/(small.offsetWidth - mask.offsetWidth);
//大图的纵向移动的坐标
var bigImgMoveY = y*maxX/(small.offsetWidth - mask.offsetWidth);
//设置图片移动
bigImg.style.marginLeft = -bigImgMoveX+"px";
bigImg.style.marginTop = -bigImgMoveY+"px";
}
</script>
</body>
</html>
效果如下:(图片可以自己找)