CSS样式
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 350px;
height: 350px;
border: 1px solid #000;
margin: 100px;
position: relative;
}
#big {
width: 400px;
height: 400px;
border: 1px solid #000;
position: absolute;
top: 0;
left: 360px;
overflow: hidden;
display: none;
}
#mask {
width: 175px;
height: 175px;
background: pink;
opacity: 0.3;
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none
}
#small {
position: relative;
}
#bigImg {
position: absolute;
left: 0;
top: 0;
}
</style>
代码结构:
<body>
<div id="box">
<div id="small">
<img src="images/iphone.jpg" alt="" id="smallImg" />
<div id="mask"></div>
</div>
<div id="big">
<img src="images/iphone_big.jpg" alt="" id="bigImg" />
</div>
</div>
</body>
JS代码:
<script>
/*
思路:
1、鼠标移入到小图区域 显示mask和big 离开时 隐藏
2、鼠标在小图区域上移动 改变mask的left和top 控制bigImg的left和top
小图显示区域的宽 / 大图显示区的宽 = 小图的宽/ 大图的宽度
*/
var box = document.querySelector("#box");
var min = document.querySelector("#small");
var move = document.querySelector("#mask");
var bigBox = document.querySelector("#big");
box.onmouseover = function () {
move.style.display = "block";
bigBox.style.display = "block";
//移动事件
box.onmousemove = function (ev) {
var e = window.event || ev;
var X = e.pageX - this.offsetLeft - move.offsetWidth / 2; //left值
var Y = e.pageY - this.offsetTop - move.offsetHeight / 2; //top值
move.style.left = X + "px";
move.style.top = Y + "px";
//边界判断
var boxW = box.offsetWidth; //盒子的占位宽
var boxH = box.offsetWidth; //盒子的占位高
var maxL = boxW - move.offsetWidth; //最大left值
var maxT = boxH - move.offsetHeight; //最大top值
//最大left值判断
if (X <= 0) {
move.style.left = 0;
} else if (X >= maxL) {
move.style.left = maxL + "px";
}
//最大top值判断
if (Y <= 0) {
move.style.top = 0;
} else if (Y >= maxL) {
move.style.top = maxT + "px";
}
//小图显示区域的宽 / 大图显示区的宽 400 = 小图的宽 350 / 大图的宽度 800
var pic = document.querySelector("#bigImg");
var imgBox = pic.offsetWidth - box.offsetWidth; //大图的最大移动距离;
//大图移动距离=小图方块移动距离*大盒子宽/方块宽;
pic.style.left = -parseFloat(move.style.left) * bigBox.offsetWidth / move.offsetWidth + "px";
pic.style.top = -parseFloat(move.style.top) * bigBox.offsetHeight / move.offsetHeight + "px";
}
}
//移出隐藏小图方块和右边大图
box.onmouseout = function () {
move.style.display = "none";
bigBox.style.display = "none";
}
</script>