功能
- 鼠标移入到smallBox上,显示mask 和 bigBox
- 鼠标移出smallBox, 隐藏mask 和 bigBox
- 鼠标在smallBox上移动 onmousemove
- mask跟随鼠标移动
- 限制mask的移动范围
- 等比例的移动大图
//css
* {
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;
}
.box img {
vertical-align: top;
}
#bigBox img {
position: absolute;
}
<div class="box" id="box">
<div id="smallBox" class="small">
<img src="images/001.jpg" width="350" alt="" />
<div id="mask" class="mask"></div>
</div>
<div id="bigBox" class="big">
<img id="bigImg" src="images/0001.jpg" width="800" alt="" />
</div>
</div>
var box = document.querySelector("#box");
var smallBox = document.querySelector("#smallBox");
var mask = document.querySelector("#mask");
var bigBox = document.querySelector("#bigBox");
var bigImg = document.querySelector("#bigImg");
smallBox.onmouseover = function () {
mask.style.display = "block";
bigBox.style.display = "block";
}
smallBox.onmouseout = function () {
mask.style.display = "none";
bigBox.style.display = "none";
}
smallBox.onmousemove = function (e) {
var x = e.pageX - box.offsetLeft - mask.offsetWidth / 2;
var y = e.pageY - box.offsetTop - mask.offsetHeight / 2;
if(x < 0){
x = 0;
}
if(y < 0){
y = 0;
}
var maxW = smallBox.offsetWidth - mask.offsetWidth;
if(x > maxW){
x = maxW;
}
var maxH = smallBox.offsetHeight - mask.offsetHeight;
if (y > maxH) {
y = maxH;
}
mask.style.left = x + "px";
mask.style.top = y + "px";
bigImg.style.left = -x * (bigImg.offsetWidth - bigBox.offsetWidth) / maxW + "px";
bigImg.style.top = -y * (bigImg.offsetHeight - bigBox.offsetHeight) / maxH + "px";
}