<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>京东商城放大镜</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
img {
display: block;
border: none;
}
#box, #boxDes {
position: absolute;
top: 50px;
left: 50px;
width: 350px;
height: 350px;
border: 1px solid #ccc;
box-shadow: 3px 3px 10px 0 #999;
overflow: hidden;
}
#boxDes {
display: none;
left: 410px;
}
#box img {
width: 100%;
height: 100%;
}
/*右侧盒子中图片的大小取决于左侧盒子和左侧MARK的比例,只有按照同样的比例进行放大才可以保证小图和大图完完整整的对应上*/
#boxDes img {
position: absolute;
top: 0;
left: 0;
width: 200%;
height: 200%;
}
#mark {
display: none;
position: absolute;
top: 0;
left: 0;
width: 175px;
height: 175px;
background: #000;
opacity: 0.5;
filter: alpha(opacity=50);
cursor: move;
}
</style>
</head>
<body>
<div id="box">
<img src="img/iphone.jpg"/>
<div id="mark"></div>
</div>
<div id="boxDes">
<img src="img/iphone_big.jpg"/>
</div>
<script type="text/javascript">
//->offset:获取当前元素距离BODY的偏移量
function offset(curEle) {
var l = curEle.offsetLeft, t = curEle.offsetTop, p = curEle.offsetParent;
while (p) {
if (navigator.userAgent.indexOf("MSIE 8") < 0) {
t += p.clientTop;
l += p.clientLeft;
}
t += p.offsetTop;
l += p.offsetLeft;
p = p.offsetParent;
}
return {top: t, left: l};
}
var box = document.getElementById("box"), mark = document.getElementById("mark");
var boxDes = document.getElementById("boxDes"), boxImg = boxDes.getElementsByTagName("img")[0];
var boxOff = offset(box);
//->computedPosition:计算当前mark盒子的位置信息
function computedPosition(e) {
e = e || window.event;
e.pageX = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
e.pageY = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
//->计算MARK的位置
var curL = e.pageX - boxOff.left - (mark.offsetWidth / 2) - 1;
var curT = e.pageY - boxOff.top - (mark.offsetHeight / 2) - 1;
//->做边界判断
var minL = 0, minT = 0, maxL = box.clientWidth - mark.clientWidth, maxT = box.clientHeight - mark.clientHeight;
curL = curL <= minL ? minL : (curL >= maxL ? maxL : curL);
curT = curT <= minT ? minT : (curT >= maxT ? maxT : curT);
mark.style.left = curL + "px";
mark.style.top = curT + "px";
//->让右侧的大图移动的轨迹和左侧mark的轨迹按照2:1的移动即可
boxImg.style.left = -curL * 2 + "px";
boxImg.style.top = -curT * 2 + "px";
}
box.onmouseenter = function (e) {
mark.style.display = "block";
boxDes.style.display = "block";
computedPosition(e);
};
box.onmousemove = computedPosition;
box.onmouseleave = function (e) {
mark.style.display = "none";
boxDes.style.display = "none";
};
</script>
</body>
</html>
放大镜
最新推荐文章于 2021-11-25 23:50:23 发布